Department of Computer Science. Georgia State University CSc 2720 – Data Structu
ID: 3890421 • Letter: D
Question
Department of Computer Science.
Georgia State University
CSc 2720 – Data Structure
Fall 2017 - Assignment #2
Due Wednesday, September 27th 2016
Note: (1) For all assignments, always use comments to explain your program.
(2) No copying allowed. If it is found that students copy from each other, all of these programs will get 0.
Description of program:
Write a Java program that will print the steps needed to solve a Towers of Hanoi puzzle given the number of disks. The program should first prompt the user for the number of disks. Then it should display the steps, one per line. Each step should indicate which peg to move a disk from, and which peg to move the disk to. The steps should also be sequentially numbered.
Upload the .java file into A2 folder of icollege.
Sample Output:
How many disks? (0 to end) 3
1: 1 to 3
2: 1 to 2
3: 3 to 2
4: 1 to 3
5: 2 to 1
6: 2 to 3
7: 1 to 3
How many disks? (0 to end) 0
Explanation / Answer
// TowerOfHanoi.java
import java.util.Scanner;
public class TowerOfHanoi
{
public static void doTowers(int total, char support, char intermediate, char finall)
{
if (total == 1)
{
System.out.println( support + " to " + finall);
}
else
{
doTowers(total - 1, support, finall, intermediate);
System.out.println( support + " to " + finall);
doTowers(total - 1, intermediate, support, finall);
}
}
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
while(true)
{
System.out.println("How many disks? (0 to end) ");
int numberOfDisks = scan.nextInt();
if(numberOfDisks == 0)
break;
doTowers(numberOfDisks, '1', '2', '3');
}
}
}
/*
output:
How many disks? (0 to end)
3
1 to 3
1 to 2
3 to 2
1 to 3
2 to 1
2 to 3
1 to 3
How many disks? (0 to end)
0
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.