Sie sind auf Seite 1von 46

Department of Computer Science

& Engineering
ARTIFICIAL
INTELLIGENCE
: CSE 452
---------------------------------------------------------------------------------------------------------------------------------
------

DESIGNPROBLEM– 1

SUBMITTED TO:

RAMANDEEP SINGH SIR

SUBMITTED BY:

PIYUSH RANA
RA1803A32
10803036
Tower of Hanoi
The Tower of Hanoi or Towers of Hanoi is a mathematical game or puzzle. It
consists of three rods, and a number of disks of different sizes which can slide onto
any rod. The puzzle starts with the disks in a neat stack in ascending order of size
on one rod, the smallest at the top, thus making a conical shape.
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.

Is the end of the world near? At a monastery in the city of Hanoi, Vietnam, a group
of monks has made it their life's work to solve the Towers problem, known due to
its location as the Towers of Hanoi. Legend has it that the world will end when the
monks finally solve the puzzle.

The puzzle is this. In the monastery are 3 pegs made of diamond. Resting on these
pegs are 64 discs made of solid gold. None of the 64 discs are the same size; in
fact, disc 1 is slightly larger in diameter than disc 2, which is slightly larger in
diameter than disc 3, which is slightly larger in diameter than disc 4, etc. The
initial configuration of the puzzle has all 64 discs piled in order of size on the first
peg with the largest disc on the bottom.
To solve the puzzle, all 64 discs must be moved to the third peg. Easy you say?
The problem is that due to the fragility of the gold, you are not allowed to rest a
larger disc on top of a smaller one, and only one disc may be removed from the
pegs at any one time.

There are many ways to solve this problem. The first is purely guess and check.
Those who fear the end of the world may be hoping that the monks are using this
approach. However, they're not; in fact, the monks all know the exact sequence of
moves to solve the problem.

Solving Towers of Hanoi

One Disc

Let's simplify the problem to clarify our thinking. Let's imagine the Towers of
Hanoi problem with only one disc.
Figure %: Towers Problem with 1 Disc

How do we solve this problem? Simple. We just move the disc on the first pole to
the third pole.

Figure %: Towers Solution for 1 disc

Two Discs
Let's make the problem slightly bigger. Imagine two discs.

Figure %: Towers Problem with 2 Discs

How do we solve this problem? Simple, again.

1. Use the one disc solution to move the top disc to the intermediate pole.
2. Use the one disc solution to move the bottom disc to the final pole.
3. Use the one disc solution to move the top disc to the final pole.
Figure %: Towers Solution for 2 Discs

Three Discs

How about with three discs?

1. Use the two disc solution to move the top discs to the intermediate pole.
2. Use the one disc solution to move the bottom disc to the final pole.
3. Use the two disc solution to move the top discs to the final pole.

$N$ Discs

So how about with $N$ Discs?

1. Use the $N-1$ disc solution to move the top discs to the intermediate pole.
2. Use the one disc solution to move the bottom disc to the final pole.
3. Use the $N-1$ disc solution to move the top discs to the final pole.

Figure %: Towers Solution for N discs

And, voila! A recursive solution to solving the Towers of Hanoi! Note that the
problem can be solved iteratively as well; however it makes much more intuitive
sense recursively.

ORIGIN

The puzzle was invented by the French mathematician Édouard Lucas in 1883.
There is a legend about a Vietnamese temple which contains a large room with
three time-worn posts in it surrounded by 64 golden disks. The priests of Hanoi,
acting out the command of an ancient prophecy, have been moving these disks, in
accordance with the rules of the puzzle, since that time. The puzzle is therefore
also known as the Tower of Brahma puzzle. According to the legend, when the last
move of the puzzle is completed, the world will end. It is not clear whether Lucas
invented this legend or was inspired by it.
If the legend were true, and if the priests were able to move disks at a rate of one
per second, using the smallest number of moves, it would take them 264−1 seconds
or roughly 585 billion years;[1] it would take 18,446,744,073,709,551,615 turns to
finish.
There are many variations on this legend. For instance, in some tellings, the temple
is a monastery and the priests are monks. The temple or monastery may be said to
be in different parts of the world — including Hanoi, Vietnam, and may be
associated with any religion. In some versions, other elements are introduced, such
as the fact that the tower was created at the beginning of the world, or that the
priests or monks may make only one move per day.
The Flag Tower of Hanoi may have served as the inspiration for the name.

TYPES OF SOLUTION

The puzzle can be played with any number of disks, although many toy versions
have around seven to nine of them. The game seems impossible to many
novices, yet is solvable with a simplealgorithm. The number of moves
required to solve a Tower of Hanoi puzzle is 2n-1, where n is the number of
disks.

Iterative solution
The following solution is a simple solution for the toy puzzle.
Alternate moves between the smallest piece and a non-smallest piece. When
moving the smallest piece, always move it in the same direction (to the right if the
starting number of pieces is even, to the left if the starting number of pieces is
odd). If there is no tower in the chosen direction, move the piece to the opposite
end, but then continue to move in the correct direction. For example, if you started
with three pieces, you would move the smallest piece to the opposite end, then
continue in the left direction after that. When the turn is to move the non-smallest
piece, there is only one legal move. Doing this will complete the puzzle using the
least amount of moves to do so.
It should perhaps be noted that this can be rewritten as a strikingly elegant set of
rules:

Simpler statement of iterative solution

For an even number of disks:

 make the legal move between pegs A and B


 make the legal move between pegs A and C
 make the legal move between pegs B and C
 repeat until complete

For an odd number of disks:

 make the legal move between pegs A and C


 make the legal move between pegs A and B
 make the legal move between pegs B and C
 repeat until complete

In each case, a total of 2n-1 moves are made.

Recursive solution

Let call the three pegs Src (Source), Aux (Auxiliary) and Dst (Destination). To
better understand and appreciate the following solution you should try solving the
puzzle for small number of disks, say, 2,3, and, perhaps, 4. However one solves
the problem, sooner or later the bottom disk will have to be moved from Src to
Dst. At this point in time all the remaining disks will have to be stacked in
decreasing size order on Aux. After moving the bottom disk from Src to Dst these
disks will have to be moved from Aux to Dst. Therefore, for a given number N of
disks, the problem appears to be solved if we know how to accomplish the
following tasks:

1. Move the top N - 1 disks from Src to Aux (using Dst as an intermediary peg)
2. Move the bottom disk from Src to Dst
3. Move N - 1 disks from Aux to Dst (using Src as an intermediary peg)

Assume there is a function Solve with four arguments - number of disks and three
pegs (source, intermediary and destination - in this order). Then the body of the
function might look like

Solve(N, Src, Aux, Dst)


if N is 0
exit
else
Solve(N - 1, Src, Dst, Aux)
Move from Src to Dst
Solve(N - 1, Aux, Src, Dst)

This actually serves as the definition of the function Solve. The function is
recursive in that it calls itself repeatedly with decreasing values of N until a
terminating condition (in our case N = 0) has been met. To me the sheer simplicity
of the solution is breathtaking. For N = 3 it translates into

1. Move from Src to Dst


2. Move from Src to Aux
3. Move from Dst to Aux
4. Move from Src to Dst
5. Move from Aux to Src
6. Move from Aux to Dst
7. Move from Src to Dst

Of course "Move" means moving the topmost disk. For N = 4 we get the following
sequence

1. Move from Src to Aux


2. Move from Src to Dst
3. Move from Aux to Dst
4. Move from Src to Aux
5. Move from Dst to Src
6. Move from Dst to Aux
7. Move from Src to Aux
8. Move from Src to Dst
9. Move from Aux to Dst
10.Move from Aux to Src
11.Move from Dst to Src
12.Move from Aux to Dst
13.Move from Src to Aux
14.Move from Src to Dst
15.Move from Aux to Dst

Recurrence relations

Let TN be the minimum number of moves needed to solve the puzzle with N disks.
From the previous section T3 = 7 andT4 = 15. One can easily convince oneself
that T2 = 3 and T1 = 1. A trained mathematician would also note that T0 = 0. Now
let us try to derive a general formula.

The recursive solution above involves moving twice (N - 1) disks from one peg to
another and making one additional move in between. It then follows that

TN ≤ TN-1 + 1 + TN-1 = 2TN-1 + 1

The inequality suggests that it might be possible to move N disks with fewer
than 2TN-1 + 1 moves. Which is actually not the case. Indeed, when the time comes
to move the bottom disk, (N - 1) smaller disks will have been moved from Src to
Aux in at least TN-1 moves. Since we are trying to use as few steps as possible, we
may assume that that portion of the task took exactly TN-1 moves. It takes just one
move to move the biggest disk from Src to Dst. One then needs exactly TN-1more
steps to finish the task. Therefore the minimum number of moves needed to solve
the puzzle with N disks equalsTN-1 + 1 + TN-1 = 2TN-1 + 1 moves.

In other words,
TN = 2TN-1 + 1

Thus we can define the quantity TN as

T0 = 0
TN = 2TN-1 + 1 for N > 0

We may compute T1 = 2T0 + 1 = 1, T2 = 2T1 + 1= 3, T3 = 2T2 + 1 = 7 and so on


sequentially.

The above expression is known as a recurrence relation which, as you might have
noticed, is but a recursive function. TN is defined in terms of only one of its
preceding values. Other recurrence relations may be more complicated, for
example,f(N) = 2f(N - 1) + 3f(N - 2). Recurrence relations appear under various
guises in numerous branches of Mathematics and applications.

Returning to the definition of TN, define SN = TN + 1. Then S0 = 1 and SN = TN + 1


= (2TN-1 + 1) + 1 = 2TN-1 + 2 = 2(TN-1 + 1) = 2SN-1. Which is to say that SN could be
defined as

S0 = 1
SN = 2SN-1 for N > 0

The latter is solved easily in the closed (non-recurrent) form SN=2N. Wherefrom

TN = 2N - 1 for N ≥ 0.

Coding Towers of Hanoi

Now that we know how to solve an $n$-disc problem, let's turn this into an
algorithm we can use.

If there is one disc, then we move 1 disc from the source pole to the destination
pole. Otherwise, we move $n-1$ discs from the source pole to the temporary pole,
we move 1 disc from the source pole to the destination pole, and we finish by
moving the $n-1$ discs from the temporary pole to the destination pole.

void TOH(int n, int p1, int p2, int p3)


{
if (n == 1) printf("Move top disc from %d to %d.\n", p1, p2);
else {
TOH(n-1, p1, p3, p2);
printf("Move top disc from %d to %d.\n", p1, p2);
TOH(n-1, p3, p2, p1);
}
}

Of course, we can simplify this to the following:

void TOH(int n, int p1, int p2, int p3)


{
if (n>1) TOH(n-1, p1, p3, p2);
printf("Move top disc from %d to %d.\n", p1, p2);
if (n>1) TOH(n-1, p3, p2, p1);
}

Actually, the whole story of the monks is just a legend. In fact, it isn't even an old
legend. The story was created in 1883 by a mathematician named Edouard Lucas.
He had invented an eight disc, three tower puzzle, and created the legend in order
to sell his product.

That being said, what if the story were true? Should we be worried about the world
ending when the monks solve the puzzle? After all, they live in the 21st century,
too, and have access to the same information about recursion that we have.

Luckily, just as mathematics helps us solve the puzzle, it also helps prove that our
grandchildren will still have a world to live in. In order to figure out how long it
will take the monks to solve the puzzle, we need to write a recurrence relation, a
recursive formula for describing the size of a recursive problem. Let's call our
recursive formula T(n), where n is the number of discs.

As seen above, the base case for the Towers of Hanoi problem is when $n$ is 1.
This is when the monks just have to move one disc from one pole to another. So
$T(1) = 1$. For the recursive case where $n != 1$, we need a more complicated
formula. The monks, in the recursive case, follow a three step procedure. They
move $n-1$ discs, then they move 1 disc, and then they move $n-1$ discs. So
$T(n) = T(n-1) + T(1) + T(n-1) = 2T(n-1) + 1$.

Now we know that to solve a Towers problem with $n$ discs takes $T(n) = 2T(n-
1) + 1$ steps. It would be nice if we had a closed-form solution to this recurrence
so that we could figure out exactly how long it will take. A closed form solution is
a formula without recursion, meaning we can simply plug in numbers and get our
answer.

Let's plug in some sizes and solve the Towers problem with those sizes to see if we
can find a closed-form solution.

• T(1) = 1
• T(2) = 3
• T(3) = 7
• T(4) = 15
• T(5) = 31
• T(6) = 63
• T(7) = 127
• T(8) = 255
• T(9) = 511
• T(10) = 1023

Notice a pattern here? $T(n) = 2^n - 1$. To prove to yourself that this is true, try
modifying your TOH code to count the number of disc moves. Create a global
variable count, run your modified TOH code, and then print out count.

Now we can easily compute how long it would take the monks to solve their 64-
disc Towers problem. $2^64 - 1$ is approximately $18.45x10^18$ (note that if you
actually tried to run the TOH code on your computer it would most likely take a
very, very long time). If the monks could move a disc in a millisecond (an
incredibly rate considering the size and weight of each disc), it would take them
approximately 584,600,000 years to solve the puzzle. It appears the world is safe
for now.
Let's look for a pattern in the number of steps it takes to move just one, two, or
three disks. We'll number the disks starting with disk 1 on the bottom.

1 disk: 1 move

Move 1: move disk 1 to post C

2 disks: 3 moves
Move 1: move disk 2 to post B
Move 2: move disk 1 to post C
Move 3: move disk 2 to post C

3 disks: 7 moves
Move 1: move disk 3 to post C
Move 2: move disk 2 to post B
Move 3: move disk 3 to post B
Move 4: move disk 1 to post C
Move 5: move disk 3 to post A
Move 6: move disk 2 to post C
Move 7: move disk 3 to post C
A. Recursive pattern

From the moves necessary to transfer one, two, and three disks, we can find a
recursive pattern - a pattern that uses information from one step to find the next
step - for moving n disks from post A to post C:

1. First, transfer n-1 disks from post A to post B. The number of moves will be
the same as those needed to transfer n-1 disks from post A to post C. Call
this number M moves. [As you can see above, with three disks it takes 3
moves to transfer two disks (n-1) from post A to post C.]
2. Next, transfer disk 1 to post C [1 move].
3. Finally, transfer the remaining n-1 disks from post B to post C. [Again, the
number of moves will be the same as those needed to transfer n-1 disks from
post A to post C, or M moves.]

Therefore the number of moves needed to transfer n disks from post A to post C is
2M+1, where M is the number of moves needed to transfer n-1 disks from post A
to post C.

Unfortunately, if we want to know how many moves it will take to transfer 100
disks from post A to post B, we will first have to find the moves it takes to transfer
99 disks, 98 disks, and so on. Therefore the recursive pattern will not be much help
in finding the time it would take to transfer all the disks.

However, the recursive pattern can help us generate more numbers to find an
explicit (non-recursive) pattern. Here's how to find the number of moves needed to
transfer larger numbers of disks from post A to post C, remembering that M = the
number of moves needed to transfer n-1 disks from post A to post C:
1. for 1 disk it takes 1 move to transfer 1 disk from post A to post C;
2. for 2 disks, it will take 3 moves: 2M + 1 = 2(1) + 1 = 3
3. for 3 disks, it will take 7 moves: 2M + 1 = 2(3) + 1 = 7
4. for 4 disks, it will take 15 moves: 2M + 1 = 2(7) + 1 = 15
5. for 5 disks, it will take 31 moves: 2M + 1 = 2(15) + 1 = 31
6. for 6 disks... ?

B. Explicit Pattern

Number of Disks Number of Moves


1 1
2 3
3 7
4 15
5 31
Powers of two help reveal the pattern:
Number of Disks (n) Number of Moves
1 2^1 - 1 = 2 - 1 = 1
2 2^2 - 1 = 4 - 1 = 3
3 2^3 - 1 = 8 - 1 = 7
4 2^4 - 1 = 16 - 1 = 15
5 2^5 - 1 = 32 - 1 = 31
So the formula for finding the number of steps it takes to transfer n disks from post
A to post B is: 2^n - 1.

From this formula you can see that even if it only takes the monks one second to
make each move, it will be 2^64 - 1 seconds before the world will end. This is
590,000,000,000 years (that's 590 billion years) - far, far longer than some
scientists estimate the solar system will last. That's a really long time!
The tower of Hanoi (commonly also known as the "towers of Hanoi"), is a puzzle
invented by E. Lucas in 1883. Given a stack of disks arranged from largest on the
bottom to smallest on top placed on a rod, together with two empty rods, the
towers of Hanoi puzzle asks for the minimum number of moves required to move
the stack from one rod to another, where moves are allowed only if they place
smaller disks on top of larger disks. The puzzle with pegs and disks is
sometimes known as Reve's puzzle.

The problem is isomorphic to finding a Hamiltonian path on an -hypercube


(Gardner 1957, 1959).

Given three rods and disks, the sequence giving the number of the disk (
to ) to be moved at the th step is given by the remarkably simple recursive
procedure of starting with the list for a single disk, and recursively
computing

(1)
For the first few values of , this gives the sequences shown in the following table.
A solution of the three-rod four-disk problem is illustrated above.

11
2 1, 2, 1
3 1, 2, 1, 3, 1, 2, 1
4 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1

As the number of disks is increases (again for three rods), an infinite sequence is
obtained, the first few terms of which are illustrated in the table above (Sloane's
A001511). Amazingly, this is exactly the binary carry sequence plus one. Even
more amazingly, the number of disks moved after the th step is the same as the
element which needs to be added or deleted in the th addend of the Ryser formula
(Gardner 1988, Vardi 1991). A simple method for hand-solving uses disks painted
with alternating colors. No two disks of the same color are ever placed atop each
other, and no disk is moved twice in a row (P. Tokarczuk, pers. comm. Jun. 23,
2004).

As a result of the above procedure, the number of moves required to solve the
puzzle of disks on three rods is given by the recurrence relation

(2)

with . Solving gives

(3)

i.e., the Mersenne numbers.

For three rods, the proof that the above solution is minimal can be achieved using
the Lucas correspondence which relates Pascal's triangle to the Hanoi graph. While
algorithms are known for transferring disks on four rods, none has been proved
minimal.

A Hanoi graph can be constructed whose graph vertices correspond to legal


configurations of towers of Hanoi, where the graph vertices are adjacent if the
corresponding configurations can be obtained by a legal move. The puzzle itself
can be solved using a binary Gray code.
Poole (1994) and Rangel-Mondragón give Mathematica routines for solving the
Hanoi towers problem. Poole's algorithm works for an arbitrary disk configuration,
and provides the solution in the fewest possible moves.

The minimal numbers of moves required to order , 2, ... disk on four rods are
given by 1, 3, 5, 9, 13, 17, 25, 33, ... (Sloane's A007664). It is conjectured that this
sequence is given by the recurrence

(4)

with and the positive floor integer solution to

(5)

i.e.,

(6)

This would then given the explicit formula

(7)

MATHEMATICAL PART:

total
number
number
of disks
of moves
1 1
2 3
3 7
4 15
5 31
Then, I tried to dissect the process of moving one tower, specifically the tower
with 5 discs. To dissect it, I kept track of what move I was on when I finally got
the nth disc off the original tower or onto the final tower (in place).

5
To get: 1 off 2 off 3 off 4 off 4 on 3 on 2 on 1 on
off/on
cumulative
1 2 4 8 16 24 28 30 31
# moves
This didn't give me any great insight at first, so then I tried to count the number of
moves between each step.

5
To get: 1 off 2 off 3 off 4 off 4 on 3 on 2 on 1 on
off/on
cumulative
1 2 4 8 16 24 28 30 31
# moves
# moves at
1 1 2 4 8 8 4 2 1
step
Ah, now we're beginning to see a pattern. Let's look now at the terms of the sum
for different numbers of discs.

Number of Total number


Terms in Sum
discs of moves
1 1 1
2 1+1+1 3
3 1+1+2+2+1 7
4 1+1+2+4+4+2+1 15
5 1+1+2+4+8+8+4+2+1 31
1 + 2 + 4 + 8 + 16 + 16 + 8 + 4 + 2 +
6 63
1
Now, consider this same table in terms of 2n.

Number of
Terms of Sum
discs
1 1
2 1 + 20 + 20
3 1 + 20 + 21 + 21 + 20
4 1 + 20 + 21 + 22 + 22 + 21 + 20
5 1 + 20 + 21 + 22 + 23 + 23 + 22 + 21 + 20
6 1 + 20 + 21 + 22 + 23 + 24 + 24 + 23 + 22 + 21 + 20
From this, I could describe the pattern of summation as:
(TH)n = 1 + 20 + 21 + 22 + 23 + . . . + 2n-3 + 2n-2 + 2n-2 + 2n-3 + . . . 23 + 22 + 21 + 20

But this is a very cumbersome formula. Notice, however that there are always two
appearances of every term. So, we can simplify somewhat by expressing 2x + 2x as
2*2x or 2x+1. This gives us a new summation seqence:

(TH)n = 20 + 21 + 22 + 23 + . . . + 2n-2 + 2n-1

Before continuing, let's verify this formula with a few known sums:

Formula Value:
Number of Known
(TH)n = 20 + 21 + 22 + 23 + . . . Equal/Unequal
Disks Sum
+ 2n-2 + 2n-1
1 1 20 = 1 Equal
0 1
2 3 2 +2 =3 Equal
3 7 20 + 21 + 22 = 7 Equal
4 15 20 + 21 + 22 + 23 = 15 Equal
Here, we can easily see the recursive formula: (TH)n = (TH)n-1 + 2n-1

At this point, I was still playing with summing particular sequences of numbers
using collapsing pairs. I found that for n=6, (TH)6 = 62 +1 = 64 -2 +1 = 26 -2 +1 =
26 -1. So, I made the guess, (TH)n = 2n -1. So, now my question was: Does 2n -1 =
1 + 21 + 22 +23+...+2n-2+ 2n-1? I decided the best approach was to continue trying to
collapse my summation. Here I returned to our familiar method of summing terms
from opposite ends of the sequence.

(TH)n = 20 + 21 + 22 + 23 + . . . + 2n-2 + 2n-1

Notice that each pair sums to 2n-1. We can use what we've learned before to figure
out how many times this sum appears. Counting from zero to n-1 gives us n terms,
or n/2 pairs. So, (TH)n = 2n-1(n/2). But this can be simplified as well, because 2n-1/2
is equivalent to 2n-2. So, (TH)n = n*2n-2. Before I continue with this formula, let's
verify it for a few known sums:
Number of Known Formula Value [(TH)n
Equal/ Unequal
Disks Sum = n*2n-2 ]
1 1 1*2-1 =1/2 Unequal
2 3 2*20 = 2 Unequal
3 7 2*21 = 4 Unequal
I'm not sure what went wrong, but let's try a slightly different collapsing pattern.
Keep the 20 alone and sum the rest as usual. Then each pair sums to 2 n. Now there
should be (n-1)/2 pairs of this value.
(TH)n = 20 + 21 + 22 + 23 + . . . + 2n-2 + 2n-1

Now, we should get the formula (TH)n = 20 + 2n(n-1)/2. Again, let's try to verify
the results.

Number of Known Formula Value [(TH)n = 20 + Equal/


Disks Sum 2n(n-1)/2] Unequal
1 1 1 + 21(0)/2 = 1 Equal
2 3 1 + 22(1/2) = 1 +4/2 = 3 Equal
3 7 1 + 23(2/2) = 9 Unequal
Foiled again.

Let's go back to the guess of (TH)n = 2n -1 and try to verify those values.

Number of Known Formula Value [(TH)n = 2n Equal/


Disks Sum -1] Unequal
1
1 1 2 -1 = 1 Equal
2 3 22 -1 = 3 Equal
3 7 23 -1 = 7 Equal
4 15 24 -1 = 15 Equal
5 31 25 -1 = 31 Equal

So, from computational verification, we have two possible summation formulas:

(TH)n = 20 + 21 + 22 + 23 + . . . + 2n-2 + 2n-1


OR (TH)n = 2n -1
Now, the major question is: Why should they be equivalent? or Where does 2n -1
come from? Let's play around with some numbers here. Let's assume that the two
expressions are equivalent:

2n -1 = 20 + 21 + 22 + 23 + . . . + 2n-2 + 2n-1
2n = 1 + 20 + 21 + 22 + 23 + . . . + 2n-2 + 2n-1
2n = 20 + 20 + 21 + 22 + 23 + . . . + 2n-2 + 2n-1
2n = 2(20) + 21 + 22 + 23 + . . . + 2n-2 + 2n-1
2n = 21 + 21 + 22 + 23 + . . . + 2n-2 + 2n-1
2n = 2(21) + 22 + 23 + . . . + 2n-2 + 2n-1
2n = 22 + 22 + 23 + . . . + 2n-2 + 2n-1
2n = 2(22) + 23 + . . . + 2n-2 + 2n-1
...
2n = 2(2n-2) +2n-1
2n = 2n-1 + 2n-1
2n = 2(2n-1)
2n = 2n.
I don't know if this proves anything or not, since we assumed they were equal to
begin with.

SUMMARY OF SOLUTIONS:

Numerical solution
(TH)50 = 1.13 * 1015
Recursive formula
(TH)n = (TH)n-1 + 2^n-1
Closed formula
(TH)n = 2n -1

The formula for the minimum number of moves with 3 pegs and n discs is
2^n - 1.

The recurrence relation that leads to this result is

u(n) = 2*u(n-1) + 1 .....................................[1]


where u(n) is number of moves with n disks present.

To see this, note that to transfer n disks to another peg we must


first transfer the top n-1 disks to the third peg (taking u(n-1)
moves) then transfer the largest disk to a vacant peg (1 move) and
then transfer n-1 disks back to the peg with the largest disk (taking
another u(n-1) moves.)

Adding these moves we get

u(n-1) + 1 + u(n-1) = 2*u(n-1) + 1

Solving this recurrence relation gives

u(n) = 2^n - 1

To prove this result you can either use a descending series of partial
sums based on the recurrence relation (1) above, leading to

1 + 2 + 2^2 + 2^3 + ..... + 2^(n-1) = (2^n -1 )/(2-1) = 2^n - 1

or you can prove the result by induction.

Inductive Proof
---------------
First show that the formula is true for n = 1.

For n = 1 the formula gives 2^1 - 1 = 1 and that is correct.

Next assume it is true for some value n = k, that is we assume the


truth of

u(k) = 2^k - 1

Now add one more disk, so that n = k+1.

From the recurrence relation (1) we have

u(k+1) = 2*u(k) + 1
= 2(2^k - 1) + 1
= 2^(k+1) - 2 + 1
= 2^(k+1) - 1

and this is the same equation we had before, except that k is replaced
by k+1. So if the result is true for n = k, then it is true for
n = k+1. But it is true for n=1, therefore it will be true for n = 2,
and if true for n = 2 it will be true for n = 3, and so on to all
positive integral values of n, by the Principle of Mathematical
Induction.

Remark 1

The latest implementation of the applet sports a "Suggest move" button that
exploits an algorithm devised by Romek Zylla who graciously put up on the Web
an explanation of his algorithm. The algorithm actually provides another, a non-
recursive solution to the puzzle.

Remark 2

There are quite a few variations on the puzzle. For example, you may want to
experiment with its bicolor or 3 colors versions.

Assumptions:

3 pegs, 3N disks of N different sizes, 3 colors of each size. Size N is the largest
disk, size 1 the smallest.

Rules: A larger disk must never sit on top of a smaller disk. Equal size disks are
OK to stack. The only allowed move is to transfer a single disk from one peg to
another.

Starting Position: Each peg holds all N disks of a single color, ordered by size
from largest (bottom) to smallest (top).
Ending Position: Same as starting position, but the colors of the stacks are rotated
among the pegs, so that no peg holds the same color stack as it did in the starting
position. In other words, a derangement of the stacks in the starting position.

Definitions:

A BASE of depth k is an arrangement of the k largest disks of each color (3k disks
altogether) across all 3 pegs, so that no two disks of the same size are on the same
peg.

A STACK of depth m is an arrangement of the m smallest disks of each color (3m


disks altogether) into a single stack on one of the pegs, so that all three disks of
each size (1 through m) are together on that one peg.

The idea:

Since there are very many positions possible, I will choose a subset of particularly
simple positions that is broad enough to include all the absolutely necessary
positions that must be used in a solution. By confining my moves to this subset, I
will get a particularly simple algorithm, although it will not be possible to prove
that it solves the puzzle in the minimum number of moves.

Since in order to effect a derangement of the largest disks, all the smaller ones
must be gathered into a single stack, a stack of depth N-1 is necessary at some
point. Since the starting and ending positions are bases of depth N, these are
necessary positions as well. The simplest definition of a subset of all positions that
would include these is this: A stack of depth k on top of a base of depth N-k. I will
choose these to be the allowed positions. The starting and ending positions fit into
this scheme with k = 0, and the intermediate stack fits with k = N-1.

I will only consider sequences of moves that start and end with allowed positions.
There are four basic operations needed:

1. MOVE(a, b) moves the top disk of peg a to peg b. MOVE is invertible, and
the inverse of MOVE(a, b) is MOVE(b, a).
2. SHIFT(a, b, c, k) moves a stack of depth k from peg a to peg b and ignores
peg c. SHIFT is invertible, and the inverse of SHIFT(a, b, c, k) is SHIFT(b,
a, c, k). It can be defined recursively just like the algorithm for the ordinary
one-color Tower of Hanoi:
3. SHIFT(a, b, c, k)
4. {
5. if k > 0
6. {
7. SHIFT(a, c, b, k-1)
8. MOVE(a, b)
9. MOVE(a, b)
10. MOVE(a, b)
11. SHIFT(c, b, a, k-1)
12. }
13.}
14.GATHER collects the top layer of disks from a base onto the bottom of a
stack of depth k-1 located at peg a, leaving the resulting larger stack on peg
c, and using peg b as a temporary location. It can be defined non-recursively
by calling SHIFT:
15.GATHER(a, b, c, k)
16.{
17. MOVE(b, c)
18. SHIFT(a, b, c, k-1)
19. MOVE(a, c)
20. SHIFT(b, c, a, k-1)
21.}
22.SPREAD is the inverse of GATHER, and distributes the bottom 3 disks
from a stack of depth k on peg a to form a new layer on top of a base, and
leaves the reduced stack on peg c, using peg b as a temporary location. It is
defined much as GATHER:
23.SPREAD(a, b, c, k)
24.{
25. SHIFT(a, b, c, k-1)
26. MOVE(a, c)
27. SHIFT(b, c, a, k-1)
28. MOVE(a, b)
29.}

Some observations:

SHIFT reverses the color order in the bottom 3 disks of the stack. However,
because SHIFT calls itself twice in each recursion, all disks above the bottom 3
have had their color order reversed an even number of times (in fact a power of 2).
Hence all the color order in the stack is preserved, except for its very bottom layer
of 3 disks. GATHER and SPREAD each call SHIFT twice, so that in practice,
even the bottom layer of the stack has its color order preserved.
GATHER and SPREAD preserve a record of the color order of the base and the
stack. If the colors are numbered 1, 2 and 3, then the color order of the top layer of
the base can be thought of as a permutation of those numbers, call it B. Similarly,
the color order in the bottom 3 disks of a stack is some permutation of [1, 2, 3]
(ordered from the top down), call it S. The calling arguments of GATHER are
some permutation of [1, 2, 3] as well, [a, b, c] = p([1, 2, 3]), where p is a
permutation operation. As is easy to check (there are only a few cases) S = p(B).
For instance, if the colors in the base are in the order 3, 2, 1, and if GATHER is
called with parameters [a, b, c] = [1, 3, 2], its permutation is (2, 3). The
permutation of the bottom 3 colors of the stack will then be (2, 3)[3, 2, 1] = [3, 1,
2].

SPREAD similarly gives B = q(S), where [c, b, a] = q-1([1, 2, 3]). Note the order
reversal here. In order for SPREAD to be a true inverse of GATHER, the stack has
to start where GATHER left it, and end where GATHER found it. Also, of course,
q is inverted because SPREAD takes S to B instead of B to S. In short, q is the
inverse of the reverse of the parameter permutation of SPREAD. Examining the
definitions of GATHER and SPREAD line by line shows that each operation in
SPREAD(c, b, a, k) is the exact inverse an operation in GATHER(a, b, c, k), and
that the operations are carried out in the reverse order.

Recursive GATHER and SPREAD:

I defined GATHER and SPREAD nonrecursively to make it clearer how they


preserve color permutation information. For any given base + stack position, there
are two possible ways to apply GATHER or SPREAD: if the stack of depth k is on
peg 1, for instance, GATHER(1, 2, 3, k) and GATHER(1, 3, 2, k) could be
applied. These would leave the stack in different positions and also leave the
bottom three disks in the new larger stack in a different color order. Therefore, the
only way to make GATHER and SPREAD recursive and still inverse of each
other, is to define a standard choice if permutation at each depth in such a way that
SPREAD is inverse to GATHER at each depth.

Such a choice would have to be made in any case, merely to make GATHER and
SPREAD recursive; the point here is that the choices must be compatible. For both
GATHER and SPREAD, the previous call to them must leave the stack in the
starting position for the next call. I will chose to make GATHER always rotate the
parameters backwards in the subroutine call, and SPREAD always rotate them
forwards, as follows (new definitions replace the old definitions):
GATHER(a, b, c, k)
{
if k > 1
{
GATHER(b, c, a, k-1)
}

MOVE(b, c)
SHIFT(a, b, c, k-1)
MOVE(a, c)
SHIFT(b, c, a, k-1)
}

SPREAD(a, b, c, k)
{
SHIFT(a, b, c, k-1)
MOVE(a, c)
SHIFT(b, c, a, k-1)
MOVE(a, b)

if k > 1
{
SPREAD(c, a, b, k-1)
}
}

With these definitions, it is easy to check that SPREAD(c, b, a, k) is the inverse of


GATHER(a, b, c, k) at the kth depth, and that the recursive calls are to SPREAD(a,
c, b, k-1) and GATHER(b, c, a, k-1), which are inverses at the k-1 depth.
Therefore, the recursive SPREAD and GATHER are inverses at all levels.

Now the solution to the 3-color Tower of Hanoi with 3N disks is:

GATHER(1, 2, 3, N)
SHIFT(3, 2, 1, N)
SHIFT(2, 1, 3, N)
SPREAD(1, 3, 2, N)

The first line gathers all the disks into a stack on peg 3, and the next two lines
move the stack to peg 1 (using 2 SHIFT calls, because doing it with just one would
leave the bottom 3 disks on the stack in the wrong order). Since GATHER has put
all the disks onto 1 peg, the SHIFT operations are equivalent to permuting the pegs
with the permutation (1, 2, 3). Normally the inverse of GATHER(1, 2, 3, N) would
be SPREAD(3, 2, 1, N), but because of the permutation of peg positions, the
correct inverse has parameter order (1, 2, 3)[3, 2, 1] = [1, 3, 2]. Because the
parameters have been rotated, SPREAD is "fooled" into distributing the colors
onto different pegs than the ones they started on. In fact, the colors of the final
position are permuted by the same permutation mentioned just above, (1, 2, 3).

In general you could solve the puzzle for whatever cyclic permutation of the colors
you wanted by defining:

PERMUTE(a, b, c, N)
{
GATHER(a, b, c, N)
SHIFT(c, b, a, N)
SHIFT(b, a, c, N)
SPREAD(a, c, b, N)
}

This will not work, I think, for non-cyclic permutations [a, b, c].

Well, that's it. It is more complicated than the solution to the 1 color Tower of
Hanoi, and it may not be optimal, but it clearly works. Perhaps some use could be
made of the fact that GATHER and SPREAD keep the color permutation
information in a recoverable form to make a true "next step" algorithm.

APPROCHES used :

1.

Move the top two disks from l to m

Move the bottom from l to r

Move the top two from m to r


2

Move the top disk from m to l

Move the bottom from m to r

Move the top froml to r

Move the top from l to m

Move the bottom from l to r


Move the top three disks from m to r

Applications

The Tower of Hanoi is frequently used in psychological research on problem


solving. There also exists a variant of this task called Tower of London for
neuropsychological diagnosis and treatment of executive functions.
The Tower of Hanoi is also used as Backup rotation scheme when performing
computer data Backups where multiple tapes/media are involved.
As mentioned above, the Tower of Hanoi is popular for teaching recursive
algorithms to beginning programming students. A pictorial version of this puzzle is
programmed into the emacs editor, accessed by typing M-x hanoi. There is also a
sample algorithm written in Prolog.
The Tower of Hanoi is also used as a test by neuropsychologists trying to
evaluate frontal lobe deficits.

ITERATIVE WAY TO SOLVE IT:


The Towers of Hanoi Problem involves moving a specified number of disks that
are all different sizes from one tower (or peg) to another. Legend has it that the
world will come to an end when the problem is solved for 64 disks. In the version
of the problem shown in Figure 5.15 there are five disks (labeled 1 through 5) and
three towers or pegs (labeled A, B, C). The goal is to move the five disks from peg
A to peg C subject to the following rules:

1. Only one disk may be moved at a time and this disk must be the top disk on
a peg.

2. A larger disk can never be placed on top of a smaller disk.

A B C
³ ³ ³
1 ÍØÍ ³ ³
2 ÍÍÍØÍÍÍ ³ ³
3 ÍÍÍÍÍØÍÍÍÍÍ ³ ³
4 ÍÍÍÍÍÍÍØÍÍÍÍÍÍÍ ³ ³
5 ÍÍÍÍÍÍÍÍÍØÍÍÍÍÍÍÍÍÍ ³ ³
ÄÄÄÄÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄÄÄÄ
ÄÄÄÄÄÄÁÄÄÄÄÄÄÄ

--------------------------------------------------------------

Analysis

The stopping cases of the problem involve moving one disk only (e.g. "move disk
2 from peg A to peg C"). A simpler problem than the original would be to move
four-disks subject to the conditions above, or three-disks, and so on. Therefore,
we want to split the original five-disk problem into one or more problems
involving fewer disks. Let's consider splitting the original problem into the three
problems below.
1. Move four disks from peg A to peg B.
2. Move disk 5 from peg A to peg C.
3. Move four disks from peg B to peg C.

Step 1 moves all disks but the largest to tower B, which is used as an auxiliary
tower. Step 2 moves the largest disk to the goal tower, tower C. Then, step 3
moves the remaining disks from B to the goal tower where they will be placed on
top of the largest disk. Let's assume that we will be able to perform step 1 and step
2 (a stopping case); Figure 5.16 shows the status of the three towers after
completing these steps. At this point, it should be clear that we can solve the
original five-disk problem
if we can complete step 3.

A B C
³ ³ ³
³ 1 ÍØÍ ³
³ 2 ÍÍÍØÍÍÍ ³
³ 3 ÍÍÍÍÍØÍÍÍÍÍÍ ³
³ 4 ÍÍÍÍÍÍÍØÍÍÍÍÍÍÍ 5 ÍÍÍÍÍÍÍØÍÍÍÍÍÍÍÍ
ÄÄÄÄÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
ÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄ

_______________________________________________________________

Unfortunately, we still don't know how to perform step 1 or step 3. However,


both these steps involve four disks instead of five so they are easier than the
original problem. We should be able to split them into simpler problems in the
same way that we split the original problem. Step 3 involves moving four disks
from tower B to tower C, so we can split it into two three-disk problems and a one-
disk problem:
3.1 Move three disks from peg B to peg A.
3.2 Move disk 4 from peg B to peg C.
3.3 Move three disks from peg A to peg C.
Figure 5.17 shows the status of the towers after completing steps 3.1 and 3.2.
We now have the two largest disks on peg C. Once we complete step 3.3 all five
disks will be on peg C as required. By splitting each n-disk problem into two
problems involving n-1 disks and a one disk problem, we will eventually reach all
cases of one disk, which we know how to solve.

A B C
³ ³ ³
³ ³ ³
1 ÍØÍ ³ ³
2 ÍÍÍØÍÍÍ ³ 4 ÍÍÍÍÍØÍÍÍÍÍ
3 ÍÍÍÍÍØÍÍÍÍÍ ³ 5 ÍÍÍÍÍÍÍØÍÍÍÍÍÍÍ
ÄÄÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
ÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄ
________________________________________________________________

Design Overview
The solution to the Towers of Hanoi Problem consists of a printed list of individual
disk moves. We need a recursive procedure which can be used to move any
number of disks from one peg to another, using the third peg as an auxiliary.

Data Requirements
Problem Inputs
The number of disks to be moved (int N)
The from peg (char FromPeg)
The to peg (char ToPeg)
The auxiliary peg (char AuxPeg)
Problem Outputs
A list of individual disk moves

Initial Algorithm
1. if N is 1 then
2. Move disk 1 from the from peg to the to peg
else
{
3. Move N-1 disks from the from peg to the auxiliary
peg using the to peg.
4. Move disk N from the from peg to the to peg.
5. Move N-1 disks from the auxiliary peg to the to
peg using the from peg.
}

If N is 1, a stopping case is reached. If N is greater than 1, the recursive step


(following else) splits the original problem into three smaller subproblems, one of
which is a stopping case. Each stopping case displays a move instruction. Verify
that the recursive step generates the three problems listed above Figure 5.15 when
N is 5, the from peg is A, and the to peg is C.
The implementation of this algorithm is shown as function Tower in Fig. 5.18.
Function Tower has four arguments. The function call statement
Tower('A', 'C', 'B', 5);
solves the problem posed earlier of moving five disks from tower A to tower C
using B as an auxiliary (see Figure 5.15).

#include <iostream.h>

void Tower(char FromPeg, char ToPeg, char AuxPeg, int N)


//Moves N disks from FromPeg to ToPeg using Auxpeg as an
//auxiliary.
//Pre : FromPeg, ToPeg, AuxPeg, and N are defined.
//Post: Display list of move instructions to transfer the disks.
{
if (N == 1)
{
cout << "Move disk 1 from peg " << FromPeg;
cout << " to peg " << ToPeg << "\n";
}
else
{ //recursive step
Tower(FromPeg, AuxPeg, ToPeg, N - 1);
cout << "Move disk " << N << " from peg "<< FromPeg;
cout << " to peg " << ToPeg << "\n";
Tower(AuxPeg, ToPeg, FromPeg, N - 1);
}
}

The stopping case (move disk 1) is implemented as a call to function cout. Each
recursive step consists of two recursive calls to Tower with a call to cout
sandwiched between them. The first recursive call solves the problem of moving
N - 1 disks to the auxiliary peg. The call to cout displays a message to move disk
N to the to peg. The second recursive call solves the problem of moving the N - 1
disks back from the auxiliary peg to the to peg.

Testing
The function call statement
Tower('A', 'C', 'B', 3);
solves a simpler three-disk problem: Move 3 disks from peg A to peg C. Its
execution is traced in Fig. 4.19; the output generated is shown in Table 5.1. Verify
for yourself that this list of steps does indeed solve the three-disk problem.

Table Output Generated by Tower ('A','C','B',3)


__________________________________________________________

Move disk 1 from peg A to peg C


Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C
________________________________________________________________
Comparison of Iteration and Recursive Procedures

It is interesting to consider that function Tower in Figure 5.18 will solve the
Tower of Hanoi Problem for any number of disks. The three-disk problem results
in a total of seven calls to function Tower and is solved by seven disk moves. The
five-disk problem would result in a total of thirty-one calls to function Tower and
is solved in thirty-one moves. In general, the number of moves required to solve
the n-disk problem is
2n - 1. Since each procedure call requires the allocation and initialization of a
local data area in memory, the computer time increases exponentially with the
problem size. For this reason, be careful about running this program with a value
of N that is larger than ten.
The dramatic increase in processing time for larger towers is a function of this
problem, not recursion. However, in general if there are recursive and iterative
solutions to the same problem, the recursive solution will require more time and
space because of the extra procedure calls. We will discuss algorithm efficiency
later.
Although recursion was not really needed to solve the simpler problems in this
section, it was extremely useful in formulating an algorithm for Towers of Hanoi.
We will see that for certain problems, recursion leads naturally to solutions that are
much easier to read and understand than their iterative counterparts. In these
cases, the benefits gained from increased clarity far outweigh the extra cost (in
time and memory) of running a recursive program.

#include<iostream.h>

#include<graphics.h>

#include<process.h>

#include<conio.h>

int a[10],b[10],c[10],tos_a=-1,tos_b=-1,tos_c=-1,n;

void push_a(int x)

tos_a++;
a[tos_a]=x;

int pop_a()

int x;

x=a[tos_a];

a[tos_a]=-1;

tos_a--;

return x;

void push_b(int x)

tos_b++;

b[tos_b]=x;

int pop_b()

int x;

x=b[tos_b];

b[tos_b]=-1;

tos_b--;

return x;

}
void push_c(int x)

tos_c++;

c[tos_c]=x;

int pop_c()

int x;

x=c[tos_c];

c[tos_c]=-1;

tos_c--;

return x;

void show()

cleardevice();

int i;

setcolor(WHITE);

line(120,100,120,300);

line(320,100,320,300);

line(520,100,520,300);

setcolor(RED);

setfillstyle(SOLID_FILL,RED);
for(i=tos_a;i>=0;i--)

rectangle(20+90-(a[tos_a-i]*10),300-(n-i)*20,220-90+(a[tos_a-
i]*10),300-(n-i)*20+20);

floodfill(20+90-(a[tos_a-i]*10)+1,300-(n-i)*20+1,RED);

for(i=tos_b;i>=0;i--)

rectangle(220+90-(b[tos_b-i]*10),300-(n-i)*20,420-90+(b[tos_b-
i]*10),300-(n-i)*20+20);

floodfill(220+90-(b[tos_b-i]*10)+1,300-(n-i)*20+1,RED);

for(i=tos_c;i>=0;i--)

rectangle(420+90-(c[tos_c-i]*10),300-(n-i)*20,620-90+(c[tos_c-
i]*10),300-(n-i)*20+20);

floodfill(420+90-(c[tos_c-i]*10)+1,300-(n-i)*20+1,RED);

void solve()

if(n%2==0)

if(tos_a==-1)
{

push_a(pop_b());

else if(tos_b==-1)

push_b(pop_a());

else

if(b[tos_b]>a[tos_a])

push_b(pop_a());

else

push_a(pop_b());

show();

getch();

if(tos_a==-1&&tos_b==-1)

exit(0);

if(tos_a==-1)

push_a(pop_c());

else if(tos_c==-1)
{

push_c(pop_a());

else

if(c[tos_c]>a[tos_a])

push_c(pop_a());

else

push_a(pop_c());

show();

getch();

if(tos_a==-1&&tos_b==-1)

exit(0);

if(tos_c==-1)

push_c(pop_b());

else if(tos_b==-1)

push_b(pop_c());

else
{

if(b[tos_b]>c[tos_c])

push_b(pop_c());

else

push_c(pop_b());

show();

getch();

else

if(tos_a==-1)

push_a(pop_c());

else if(tos_c==-1)

push_c(pop_a());

else

if(c[tos_c]>a[tos_a])

push_c(pop_a());
else

push_a(pop_c());

show();

getch();

if(tos_a==-1&&tos_b==-1)

exit(0);

if(tos_a==-1)

push_a(pop_b());

else if(tos_b==-1)

push_b(pop_a());

else

if(b[tos_b]>a[tos_a])

push_b(pop_a());

else

push_a(pop_b());

show();
getch();

if(tos_a==-1&&tos_b==-1)

exit(0);

if(tos_c==-1)

push_c(pop_b());

else if(tos_b==-1)

push_b(pop_c());

else

if(b[tos_b]>c[tos_c])

push_b(pop_c());

else

push_c(pop_b());

show();

getch();

if(tos_a!=-1||tos_b!=-1)

solve();
}

void main()

int d=DETECT,m;

int i;

cout<<"Enter the number of discs(Max 10):";

cin>>n;

for(i=0;i<10;i++)

a[i]=b[i]=c[i]=-1;

for(i=n;i>0;i--)

push_a(i);

initgraph(&d,&m,"\\tc\\bgi");

show();

getch();

solve();

getch();

closegraph();