Write a recursive method named hanoi that prints a solution to the classic Towers of Hanoi puzzle. Your method should accept three integer parameters representing the number of disks, the starting page number, and ending peg number. Your method should print the solution to the game to move from the given start peg to the given end peg. For example, the call of hanoi(3, 1, 3); should print the following output to move the three pegs from peg

Respuesta :

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);

   }

}

Ver imagen sandlee09