Java Help Write and test a recursive method that solves the

Java Help

Write and test a recursive method that solves the Towers of Hanoi puzzle. Your

method hanoi(...) should have four parameters: int n , char start , char finish , char using

Your test call should be

hanoi(5, ‘A’, ‘B’, ‘C’);

where the pegs are called ‘A ’ , ‘B ’ , and ‘C ’ , and you are trying to move five disks from

‘A ’ to ‘B ’ , using ‘C ’ .

For example, hanoi (2, ‘A ’ , ‘B ’ , ‘C ’ ) will output:

Move a disk from A to C

Move a disk from A to B

Move a disk from C to B

Hint : hanoi(5, ‘A ’ , ‘B ’ , ‘C ’ ) can be done in three steps:

hanoi(4, ‘A ’ , ‘C ’ , ‘B ’ );

Move a disk from A to B ;

hanoi(4, ‘C ’ , ‘B ’ , ‘A ’ );

Solution

import java.util.Scanner;
public class TowersOfHanoi {

public void hanoi(int n, String start, String auxiliary, String end) {
if (n == 1) {
System.out.println(start + \" -> \" + end);
} else {
hanoi(n - 1, start, end, auxiliary);
System.out.println(start + \" -> \" + end);
hanoi(n - 1, auxiliary, start, end);
}
}

public static void main(String[] args) {
TowersOfHanoi towersOfHanoi = new TowersOfHanoi();
System.out.print(\"Enter number of discs: \");
Scanner scanner = new Scanner(System.in);
int discs = scanner.nextInt();
towersOfHanoi.hanoi(discs, \"A\", \"B\", \"C\");
}
}==================================================

Output:

Enter number of discs: 3
A -> C
A -> B
C -> B
A -> C
B -> A
B -> C
A -> C

Java Help Write and test a recursive method that solves the Towers of Hanoi puzzle. Your method hanoi(...) should have four parameters: int n , char start , cha

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site