Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. There are three towers which can be represented by source, temp and destinati

ID: 3757832 • Letter: 1

Question

1. There are three towers which can be represented by source, temp and destination

2. We have a stack of n disks on the source tower; all the disks have a different diameter. The largest disk is at the bottom and the smallest is at the top.

3. The goal is to transfer all the disks, one at a time, to the destination tower using all three towers for help. No larger disk may ever be on top of a smaller disk.

The recursion solution to the problem for the general case (n-1):

1. Transfer the top(n-1) disks from the source tower to the temporary tower.

2. Transfer the one remaining disk (the largest) from the source to the destination

3. Transfer the (n-1) disks from the temporary to the destination base case : n=0, no disks to transfer

Code the tower of hanoi problem. Your solution should output to the user which disks are being transferred and to which tower as the program is executing. Submit your .java, .class files and screenshot of your code.

Explanation / Answer

import java.util.Scanner;

public class TowersOfHanoi {

   public static void main(String[] args) {

   Scanner sc = new Scanner(System.in);

   System.out.println("Enter number of disks: ");

int nDisks = sc.nextInt();

doTowers(nDisks, 'A', 'B', 'C');

   }

   public static void doTowers(int n, char from,

   char inter, char to) {

if (n == 1){

   System.out.println("Disk 1 from "

   + from + " to " + to);

}else {

   doTowers(n - 1, from, to, inter);

   System.out.println("Disk "

   + n + " from " + from + " to " + to);

   doTowers(n - 1, inter, from, to);

}

   }

}