Question 2 [35 marks] - Towers of Hanoi

You've got three vertical pegs. On the leftmost peg is a stack of disks of decreasing size, with the largest peg at the bottom. The middle and rightmost pegs are empty.

You want to move the stack of disks on to the rightmost peg. The middle peg may be used for temporary storage of pegs. However, only one disk may be moved at a time, from any peg to any other peg. A larger disk can never be placed on top ofa smaller disk.

Write a method public void pegs (int from, int to, int n) that solves this for n pegs moving from peg from to peg to, printing out each move as a line of text of the form "Moving disk from peg to peg "


View the source code

Back