So i have created a towers of hanoi problem using recursion but i have to use st
ID: 3926702 • Letter: S
Question
So i have created a towers of hanoi problem using recursion but i have to use stacks to represent the pegs and ints to represent the disks, and “A,” “B,” and “C,” as labels for the pegs. I can use the stacks class built into Java but i am confused on how to use it with the code that i have already written and it fully works. How would I use stacks to represent stacks and the push and pop function to move the blocks.
import java.util.Scanner;
public class TowersofHanoi {
static int count = 0;
//Disk A = source, disk B = spare, disk C = dest
public static void Disk(int n, char A, char B, char C){
// If: disk == 1, then move the disk from the source to the dest
if (n == 1){
System.out.println("Move disk " + n + " from " + A + " to " + C);
/*
Else: move n-1 disk from A to B, so basically B becomes C
temporarily and C becomes B. Then once that is done we move the largest
piece from A to C, then finally B becomes A temporarily and A becomes B
temporarily to move the pieces to the end which is C.
*/
} else {
Disk(n-1, A, C, B);
System.out.println("Move disk " + n + " from " + A + " to " + C);
Disk(n-1, B, A, C);
}
count++; //keeps a count for the number of moves made.
}
//This is the main method that takes in the user input of how many disks that
//the player would like to use.
public static void main(String[] args) {
int n;
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number of disks: ");
n = kb.nextInt();
System.out.println("These are the moves that need to be made: ");
Disk(n, 'A', 'B', 'C' );
System.out.println(count + "-Is the total number of moves that were made. ");
}
}
Explanation / Answer
import java.util.Scanner;
public class TowersofHanoi {
public static void main(String[] args) {
int nDisks = 3;
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from,
char inter, char to) {
if (topN == 1){
System.out.println("Disk 1 from "
+ from + " to " + to);
}else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk "
+ topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.