초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 Ruby 소스이다.
#
# 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
'프로그래밍 > Ruby' 카테고리의 다른 글
스트링 배열 정렬(sorting)하기 with Ruby (0) | 2009.04.15 |
---|---|
Pollard's rho method 소개: 정수의 인수분해(factorizing integers) with Ruby (0) | 2009.03.24 |
문자열 거꾸로 하기 with Ruby (0) | 2009.01.25 |
손으로 만드는 나눗셈 계산표 with Ruby (0) | 2008.05.16 |
클래스 상속(subclassing) 예제 with Ruby (0) | 2008.04.05 |