Linux Tips and Tricks

Linux Tips and Tricks

Tower of Hanoi – in Shell Script

June4

What is Tower of Hanoi ?

The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

  •     Only one disk may be moved at a time.
  •     Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  •     No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves.

More information  about the Tower of Hanoi

Shell script for this puzzle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ cat hanoi.sh
#!/bin/bash
#---------------------------------------
#Author : Kamaraj Subramanian
#---------------------------------------
echo -n "How Many Disks? : "
read disk
echo "-------------STARTS---------"
for (( x=1; x < (1 << $disk ); x++ ))
do
i=$((($x & $x - 1 ) % 3))
j=$(((($x | $x - 1 ) + 1 ) % 3))
echo "Move from tower $i to tower $j"
done

Solution :

1
2
3
4
5
6
7
8
9
10
$ ./hanoi.sh
How Many Disks? : 3
-------------STARTS---------
Move from tower 0 to tower 2
Move from tower 0 to tower 1
Move from tower 2 to tower 1
Move from tower 0 to tower 2
Move from tower 1 to tower 0
Move from tower 1 to tower 2
Move from tower 0 to tower 2
posted under Uncategorized

Email will not be published

Website example

Your Comment:


Recent Comments

    Categories