This is how I write the Tower of Hanoi solution:
public static String hanoi(int nDisks, int fromPeg, int toPeg) { int helpPeg; String helpSol1, helpSol2, MyStep, mySol; // Contains moves if ( nDisks == 1 ) { return fromPeg + " -> " + toPeg + "\n"; } else { helpPeg = 6 - fromPeg - toPeg; // Delegate: helpSol1 = hanoi(nDisks-1, fromPeg, helpPeg); helpSol2 = hanoi(nDisks-1, helpPeg, toPeg); // Use the solutions of smaller problems to solve my problem: MyStep = fromPeg + " -> " + toPeg + "\n"; mySol = helpSol1 + MyStep + helpSol2; // + = concatenate return mySol;; } } |