Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this iterative Tower of Hanoi work? C [duplicate]

Possible Duplicate:
How does this work? Weird Towers of Hanoi Solution

While surfing Google, i found this interesting solution to Tower Of Hanoi which doesn't even use stack as data structure.

Can anybody explain me in brief, what is it actually doing?

Are this solution really acceptable?

Code

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int n, x;
   printf("How many disks?\n");
   scanf("%d", &n);
   printf("\n");
   for (x=1; x < (1 << n); x++)
      printf("move from tower %i to tower %i.\n",
         (x&x-1)%3, ((x|x-1)+1)%3);
return 0;
}

Update: What is the hard-coded number 3 doing in here?

like image 729
TCM Avatar asked May 20 '10 02:05

TCM


People also ask

How does the Tower of Hanoi work?

The rules of the puzzle are essentially the same: disks are transferred between pegs one at a time. At no time may a bigger disk be placed on top of a smaller one. The difference is that now for every size there are two disks: one black and one white. Also, there are now two towers of disks of alternating colors.

Can we solve Tower of Hanoi problem with iterative method?

The Tower of Hanoi is a mathematical puzzle. It consists of three poles and a number of disks of different sizes which can slide onto any poles. The puzzle starts with the disk in a neat stack in ascending order of size in one pole, the smallest at the top thus making a conical shape.

How many moves does it take to solve the Tower of Hanoi for 2 disks?

The original Tower of Hanoi puzzle, invented by the French mathematician Edouard Lucas in 1883, spans "base 2". That is – the number of moves of disk number k is 2^(k-1), and the total number of moves required to solve the puzzle with N disks is 2^N - 1.


1 Answers

Might be easier to see in PSEUDOCODE:

GET NUMBER OF DISKS AS n
WHILE x BETWEEN 1 INCLUSIVE AND 1 LEFT-SHIFTED BY n BITS
    SUBTRACT 1 FROM n, DIVIDE BY 3 AND TAKE THE REMAINDER AS A
    OR x WITH x-1, ADD 1 TO THAT, DIVIDE BY 3 AND TAKE THE REMAINDER AS B
    PRINT "MOVE FROM TOWER " A " TO TOWER " B
    ADD 1 TO x

1 LEFT SHIFTED BY n BITS is basically 2 to the power of n, 16 in the case of 4 disks.

If you walk through this sequence manually, you should see the progression of movement of the disks. http://library.ust.hk/images/highlights/Tower_of_Hanoi_4.gif

like image 75
Robert Harvey Avatar answered Sep 23 '22 04:09

Robert Harvey