import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Recursion! * The towers of Hanoi * @author gtowell * Created Oct 2019 */ public class TowersOfHanoi { /** The number of disks in the tower */ private int count = 0; /** * Doing all the recursive work. This fucntion will print out the * sequence of moved needed to solve a tower of hanoi problem of a given height * @param n the height of the tower * @param start The tower that the disks are on * @param auxiliary The spare tower * @param end The Tower that you want disks to move to */ public void solve(int n, String start, String auxiliary, String end) { if (n == 1) { // base case of the recursion count++; System.out.println(count + " " + start + " -> " + end); return; } else { // doing the work. solve(n - 1, start, end, auxiliary); count++; System.out.println(count + " " + start + " -> " + end); solve(n - 1, auxiliary, start, end); } return; } /** * Run the code, getting the number of disks in the twoer from the user. * @param args */ public static void main(String[] args) { TowersOfHanoi towersOfHanoi = new TowersOfHanoi(); System.out.print("Enter number of discs: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { int discs = Integer.parseInt(br.readLine()); towersOfHanoi.solve(discs, "A", "B", "C"); } catch (IOException ee) { System.err.println("Read failure " + ee); } } }