초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 Ruby 소스이다.

# Filename: makeMultTable.rb
#
#     Print a multiplication table.
#
#     Execute: ruby makeMultTable.rb 230 5100
#
# Date: 2009/03/06
#
#

def printUsing()
    print "Using: ruby makeMultTable.rb [number1] [number2]\n"
    print "Print a multiplication table for the given two integers.\n"
end

def printMultTable(x, y)
    nx = x
    if nx < 0
        nx = -nx
    end
    ny = y
    if ny < 0
        ny = -ny
    end
    ntail1 = 0
    ntail2 = 0
    while (nx % 10 == 0)
        nx = nx / 10
        ntail1 = ntail1 + 1
    end
    while (ny % 10 == 0)
        ny = ny / 10
        ntail2 = ntail2 + 1
    end
    z = nx * ny
    strZ = "%d" % z
    strX = "%d" % nx
    strY = "%d" % ny
    n = strY.length
    zeros  = "0000000000000000000000000000000000000000"
    whites = "                                        "
    bars   = "----------------------------------------"
    loffset = "       "
    line4 = loffset + strZ
    line1 = loffset + whites[0 ... strZ.length - strX.length] + strX
    line2 = "   x ) " +  whites[0 ... strZ.length - strY.length] + strY
    line3 = "     --" +  bars[0 ... strZ.length]
    print line1 + zeros[0 ... ntail1] + "\n"
    print line2 + zeros[0 ... ntail2] + "\n"
    print line3 + "\n"
    if (strY.length > 1)
        for i in 0...strY.length
            y1 = strY[strY.length - i - 1 ... strY.length - i].to_i
            if (y1 != 0)
                strT = "%d" % (nx * y1)
                print loffset + whites[0 ... strZ.length - strT.length - i] + strT + "\n"
            end
        end
        print line3 + "\n"
    end
    print line4 + zeros[0 ... ntail1] + zeros[0 ... ntail2] + "\n"
end

if (ARGV.length >= 2)
    x = ARGV[0].to_i
    y = ARGV[1].to_i
    print "\n"
    printMultTable(x, y)
else
    printUsing()
end




실행> ruby makeMultTable.rb 230 5100
결과>

          230
   x )   5100
     ------
         23
       115
     ------
       1173000

 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,