import java.util.*; /** A program to solve the towers of hanoi. */ public class towers { /** * A method to move n disks from one peg to another. * @param disks - the number of disks to move * @param from - the index of the peg from which the pegs should be transferred * @param to - the index of the peg to which the pegs should be transferred * @param using - the intermediate peg * @param lists - the array of lists containing info about which disks are on which pegs **/ public static void moveMany(int disks, int from, int to, int using, ArrayList[] lists){ //base case //there are no disks to move, so return if (disks == 0) { return; } //move n-1 disks to the intermediate peg moveMany(disks-1, from, using, to, lists); //move nth disk to target peg moveOne(lists[from-1], lists[to-1]); //print current state printLists(lists); //move n-1 disks to final peg moveMany(disks-1, using, to, from, lists); } /** * A method to move one disk. * @param fromlist - the list of disks from which the top will be moved * @param tolist - the list of disks to which the top of from list will be moved **/ public static void moveOne(ArrayList fromlist, ArrayList tolist) { //remove top peg from fromlist int elt = fromlist.remove(0); //add top peg to top of tolist tolist.add(0, elt); } /** * A method to print the current state of the pegs. * @param lists - the array containing a list representing the state of each peg **/ public static void printLists(ArrayList[] lists) { //print contents of first peg System.out.print("["); for(int i = 0; i < lists[0].size(); i++) { System.out.print(lists[0].get(i)); } System.out.print("]"); //print contents of second peg System.out.print("["); for(int i = 0; i < lists[1].size(); i++) { System.out.print(lists[1].get(i)); } System.out.print("]"); //print contents of third peg System.out.print("["); for(int i = 0; i < lists[2].size(); i++) { System.out.print(lists[2].get(i)); } System.out.println("]"); } /** * Main method to run the program. * usage: java towers **/ public static void main(String[] args){ //if user did not enter number of disks as command line argument, print usage and exit if (args.length < 1) { System.out.println("usage: java towers "); System.exit(1); } //parse number entered by use to int int NUM_DISKS = 0; try { NUM_DISKS = Integer.parseInt(args[0]); } catch(NumberFormatException nfe) { //if user entered a string, print usage and exit System.out.println("usage: java towers "); System.exit(1); } //create array of lists representing the state of each peg //causes compilation warning, unchecked conversion //ignore for now ArrayList[] lists = new ArrayList[3]; lists[0] = new ArrayList(); lists[1] = new ArrayList(); lists[2] = new ArrayList(); //add n disks to first peg for(int i = 0; i < NUM_DISKS; i++) { lists[0].add(i+1); } //move n disks from peg 1 to 3 using 2 as intermediate moveMany(lists[0].size(), 1, 3, 2, lists); } }