초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 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

 

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

 

Posted by Scripter
,