Answer:
Explanation:
The following recursive method is written in Java. It creates a simulation of the towers of Hanoi and outputs every step-by-step instruction on how to solve it. The output for the code can be seen in the attached picture below.
class Brainly {
public static String hanoi(int numOfDisks, int startPeg, int endPeg) {
int helpPeg;
String sol1, sol2, MyStep, mysol; // Contains moves
if (numOfDisks == 1) {
return "Move from " + startPeg + " to " + endPeg + "\n";
} else {
helpPeg = 6 - startPeg - endPeg; // Because startPeg + helpPeg + endPeg = 6
sol1 = hanoi(numOfDisks - 1, startPeg, helpPeg);
MyStep = "Move from " + startPeg + " to " + endPeg + "\n";
sol2 = hanoi(numOfDisks - 1, helpPeg, endPeg);
mysol = sol1 + MyStep + sol2; // + = String concatenation !
return mysol;
}
}
public static void main(String[] args) {
String output = hanoi(3, 1, 3);
System.out.println(output);
}
}