초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 Groovy 소스이다.
* Filename: makeMultTable.groovy
*
* Print a multiplication table.
*
* Execute: groovy makeMultTable.groovy 230 5100
*
* Date: 2009/03/06
* Author: pkim (AT) scripts.pe.kr
*/
import java.io.*;
import java.util.*;
def printUsing() {
println "Using: groovy makeMultTable.groovy [number1] [number2]"
println "Print a multiplication table for the given two integers."
}
def printMultTable(x, y) {
long nx = (x >= 0L) ? x : - x;
long ny = (y >= 0L) ? y : - y;
int ntail1 = 0;
int ntail2 = 0;
while (nx % 10 == 0) {
nx = nx / 10;
ntail1++;
}
while (ny % 10 == 0) {
ny = ny / 10;
ntail2++;
}
long z = nx * ny;
def strZ = "" + z;
def strX = "" + nx;
def strY = "" + ny;
def n = strY.length();
def zeros = "0000000000000000000000000000000000000000";
def whites = " ";
def bars = "----------------------------------------";
def line1, line2, line3, line4;
def loffset = " ";
line4 = loffset + strZ;
line1 = loffset + whites.substring(0, strZ.length() - strX.length()) + strX;
line2 = " x ) " + whites.substring(0, strZ.length() - strY.length()) + strY;
line3 = " --" + bars.substring(0, strZ.length());
println(line1 + zeros.substring(0, ntail1));
println(line2 + zeros.substring(0, ntail2));
println(line3);
if (strY.length() > 1) {
def y1;
def strT;
for (int i = 0; i < strY.length(); i++) {
y1 = Integer.parseInt(strY.substring(strY.length() - i - 1, strY.length() - i));
if (y1 != 0) {
strT = "" + (nx * y1);
println(loffset + whites.substring(0, strZ.length() - strT.length() - i) + strT);
}
}
println(line3);
}
println(line4 + zeros.substring(0, ntail1) + zeros.substring(0, ntail2));
}
long x, y;
if (args.length >= 2) {
x = Integer.parseInt(args[0]);
y = Integer.parseInt(args[1]);
println("");
printMultTable(x, y);
}
else {
printUsing();
}
실행> groovy makeMultTable.groovy 230 5100
결과>
230 x ) 5100 ------ 23 115 ------ 1173000
'프로그래밍 > Groovy' 카테고리의 다른 글
스트링 배열 정렬(sorting)하기 with Groovy (0) | 2009.04.15 |
---|---|
Pollard's rho method 소개: 정수의 인수분해(factorizing integers) with Groovy (0) | 2009.03.24 |
문자열 거꾸로 하기 with Groovy (0) | 2009.01.25 |
손으로 만드는 나눗셈 계산표 with Groovy (0) | 2008.05.16 |
클래스 상속(subclassing) 예제 with Groovy (0) | 2008.04.05 |