logo CodeStepByStep logo

hanoi

Language/Type: PHP recursion

The Towers of Hanoi is a game where you have three pegs (#1, #2, and #3) and some circular disks of different sizes that slide onto the pegs. They all start on one peg, largest to smallest (largest on the bottom). The goal is to move all the disks to another peg by following these rules: you may only move one disk at a time from peg to peg; no disk may be placed on top of a smaller disk.

figure

Write a recursive function named hanoi that prints a solution to the classic Towers of Hanoi puzzle. Your function should accept three integer parameters representing the number of disks, the starting peg number, and ending peg number. Your function 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 #1 to peg #3:

move disk 1 from peg 1 to peg 3
move disk 2 from peg 1 to peg 2
move disk 1 from peg 3 to peg 2
move disk 3 from peg 1 to peg 3
move disk 1 from peg 2 to peg 1
move disk 2 from peg 2 to peg 3
move disk 1 from peg 1 to peg 3

Constraints: Your solution should be recursive and should not use any loops or data structures.

Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.