/*
* Created on 2005. 2. 2.
* @author DaeGon Kim
*
*/
public class Honai {
public static int moveN = 0;
public static void main(String[] args) {
/* check number of input arguments */
if ( args.length != 2 ) {
System.out.println("Usage : java Honai [#disks] [start]");
System.exit(0);
}
/* convert input and check the value */
int n = Integer.parseInt(args[0]);
int start = Integer.parseInt(args[1]);
if ( n < 1 ) {
System.out.println("Number of disk should be greater than 1");
System.exit(0);
}
if ( start == 1 ) {
/* call recursive method */
moves(1, n, start, 3);
} else if ( start == 3 ) {
/* call recursive method */
moves(1, n, start, 1);
} else {
System.out.println("start should be 1 or 3");
System.exit(0);
}
System.out.println("The number of moves is " + moveN);
}
public static void moves(int start, int end, int source, int dest) {
int n = end - start + 1;
/* base case */
if ( n == 1 ) {
System.out.println("Move disk["+ start + "] from peg[" +
source + "] to peg[" + 2 + "]");
moveN++;
System.out.println("Move disk["+ start + "] from peg[" +
2 + "] to peg[" + dest + "]");
moveN++;
/* inductive step */
} else {
moves(start, end-1, source, dest);
System.out.println("Move disk["+ end + "] from peg[" +
source + "] to peg[" + 2 + "]");
moveN++;
moves(start, end-1, dest, source);
System.out.println("Move disk["+ end + "] from peg[" +
2 + "] to peg[" + dest + "]");
moveN++;
moves(start, end-1, source, dest);
}
}
}
이전 글 : FreeBSD의 차세대 대칭형 멀티 프로세싱, SMPng
다음 글 : MySQL 트리거 미리 배우기
최신 콘텐츠