Hanoitower.java ¶
~cpp public class HanoiTower { Tower towers[] = new Tower[3]; public HanoiTower() { for(int i=0; i<3; i++) towers[i] = new Tower(); } public void solve(int numOfDiscs) { for(int i=numOfDiscs; i>0; i--) towers[0].putOnDisc(i); moveDiscs(numOfDiscs, 0); } public void moveDiscs(int numOfDiscs, int from) { int to = (from==0)?1:0; if( numOfDiscs > 3 ) { moveDiscs(numOfDiscs-1, to); } else { towers[2].bringDisc(towers[from]); towers[to].bringDisc(towers[from]); towers[to].bringDisc(towers[2]); towers[2].bringDisc(towers[from]); towers[from].bringDisc(towers[to]); towers[2].bringDisc(towers[to]); towers[2].bringDisc(towers[from]); } } public boolean verifyAllDiscsAreMoved(){ towers[2].showDiscs(); return (towers[0].isEmpty() && towers[1].isEmpty() ); } }
Tower.java ¶
~cpp import java.util.Vector; import java.util.Enumeration; public class Tower { Vector discsAtPillar = new Vector(); public Tower() { System.out.println("Tower Created."); } public boolean isEmpty() { return discsAtPillar.isEmpty(); } public boolean movable(Integer discNum){ if( discsAtPillar.isEmpty() ) return true; Object lastObj = discsAtPillar.lastElement(); Integer iObj = (Integer)lastObj; if( iObj.intValue() > discNum.intValue() ) return true; else return false; } public void putOnDisc(int discNum) { Integer i = new Integer(discNum); discsAtPillar.add(i); } public void removeTopDisc() { discsAtPillar.removeElementAt(discsAtPillar.size()-1); } public Integer getTopDisc() { Integer topDisc = (Integer)(discsAtPillar.lastElement()); return topDisc; } public void showDiscs() { Enumeration enum = discsAtPillar.elements(); while(enum.hasMoreElements()) { Integer i = (Integer)(enum.nextElement()); System.out.println(i); } } public boolean bringDisc(Tower from) { Integer discNum = from.getTopDisc(); if( movable(discNum) ) { // from 에서 꺼내와 this 에 넣는다. from.removeTopDisc(); discsAtPillar.add(discNum); return true; } else { System.out.println("이동에러!"); return false; } } }