Pure Programmer
Blue Matrix


Cluster Map

Project: Tower of Hanoi

The [[Tower of Hanoi]] is a puzzle played with disks and pegs. The idea is to move a tower of disks from one peg to another subject to certain restrictions:

  1. Only one disk can be moved at a time
  2. Each move consists of taking the upper disk from one of the pegs and placing it on top of another stack or on an empty peg
  3. A larger disk can not be placed on a smaller disk

Write a program that uses a recursive function to solve the Tower of Hanoi puzzle with three pegs and any number of disks. Print out the configuration every 1, 5, 10 or other multiple of 5 moves depending on the number of moves it takes to solve so that about 7 moves of the solution are displayed. The number of moves (`m`) it takes to solve the puzzle depends on the number of disks (`n`) and is `m = 2^n - 1`

See [[Tower of Hanoi Algorithm]]
See [[Tower of Hanoi Animation]]

Output
$ perl TowerOfHanoi.pl 3 Move: 0 1 | | 2 | | 3 | | ========= Move: 1 | | | 2 | | 3 | 1 ========= Move: 2 | | | | | | 3 2 1 ========= Move: 3 | | | | 1 | 3 2 | ========= Move: 4 | | | | 1 | | 2 3 ========= Move: 5 | | | | | | 1 2 3 ========= Move: 6 | | | | | 2 1 | 3 ========= Move: 7 | | 1 | | 2 | | 3 ========= $ perl TowerOfHanoi.pl 5 Move: 0 1 | | 2 | | 3 | | 4 | | 5 | | ========= Move: 5 | | | | | | 1 | | 4 | | 5 2 3 ========= Move: 10 | | | | | | | | | 2 1 | 5 4 3 ========= Move: 15 | | | | 1 | | 2 | | 3 | 5 4 | ========= Move: 20 | | | | | | | | 1 | | 2 3 4 5 ========= Move: 25 | | | | | | | | 1 2 | 4 3 | 5 ========= Move: 30 | | | | | 2 | | 3 | | 4 1 | 5 ========= Move: 31 | | 1 | | 2 | | 3 | | 4 | | 5 =========

Solution