Jump to content

Tower of Hanoi: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Added Other name to problem.
m Added citation
 
(178 intermediate revisions by 99 users not shown)
Line 1: Line 1:
{{short description|Mathematical game or puzzle}}
{{Short description|Mathematical puzzle game}}
{{about|the mathematical disk game|the card game|Tower of Hanoy|the Vietnamese skyscraper|Keangnam Hanoi Landmark Tower}}<!--"Hanoy" here is the actual spelling used in the card game title, not a typo-->
{{about|the mathematical disk game|the card game|Tower of Hanoy|the Vietnamese skyscraper|Landmark 72}}
<!--"Hanoy" here is the actual spelling used in the card game title, not a typo-->

[[File:Tower of Hanoi.jpeg|300px|thumb|A model set of the Tower of Hanoi (with 8 disks)]]
[[File:Tower of Hanoi.jpeg|300px|thumb|A model set of the Tower of Hanoi (with 8 disks)]]
[[File:Tower of Hanoi 4.gif|300px|thumb|An animated solution of the '''Tower of Hanoi''' puzzle for ''T''(4, 3)]]
[[File:Tower of Hanoi 4.gif|300px|thumb|An animated solution of the '''Tower of Hanoi''' puzzle for ''T''(4, 3)]]
[[File:UniversumUNAM34.JPG|thumb|300px|Tower of Hanoi interactive display at Mexico City's [[Universum (UNAM)|Universum Museum]]]]
[[File:UniversumUNAM34.JPG|thumb|300px|Tower of Hanoi interactive display at Mexico City's [[Universum (UNAM)|Universum Museum]]]]
The '''Tower of Hanoi''' (also called '''The problem of Benares Temple'''<ref>{{Cite web|title=A000225 - OEIS|url=https://oeis.org/A000225#:~:text=for%20the%20problem%20of%20Benares%20Temple,%20i.e.,%20three%20diamond%20needles%20with%20n%20discs%20ordered%20by%20decreasing%20size%20on%20the%20first%20needle%20to%20place%20in%20the%20same%20order%20on%20the%20third%20one,%20without%20ever%20moving%20more%20than%20one%20disc%20at%20a%20time%20and%20without%20ever%20placing%20one%20disc%20at%20the%20top%20of%20a%20smaller%20one|access-date=2021-09-03|website=oeis.org}}</ref> or '''Tower of Brahma''' or '''Lucas' Tower'''<ref>{{cite book |last=Hofstadter |first=Douglas R. |title=Metamagical Themas : Questing for the Essence of Mind and Pattern |url=https://archive.org/details/metamagicalthema0000hofs |url-access=registration |year=1985 |publisher=Basic Books |location=New York |isbn=978-0-465-04540-2}}</ref> and sometimes pluralized as '''Towers''', or simply '''pyramid puzzle'''<ref>{{cite journal |journal=The Mathematics Teacher |date=1963 |volume=56 |page=84 |url=https://www.google.com/books/edition/The_Mathematics_Teacher/edoVAAAAIAAJ?gbpv=1&bsq=tower+hanoi+pyramid+puzzle |access-date=9 March 2021 |publisher=National Council of Teachers of Mathematics |doi=10.5951/MT.56.2.0084 |issn=0025-5769|title=A device for demonstrating some elementary properties of integers |last1=Cohn |first1=Ernst M. |issue=2 }}</ref>) is a [[mathematical game]] or [[puzzle]] consisting of three rods and a number of disks of various [[diameter]]s, which can slide onto any rod. The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top, thus approximating a [[cone|conical]] shape. The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules:
The '''Tower of Hanoi''' (also called '''The problem of Benares Temple'''<ref name=oeis>{{Cite web|title=A000225 - OEIS|url=https://oeis.org/A000225|access-date=2021-09-03|website=oeis.org}}</ref> or '''Tower of Brahma''' or '''Lucas' Tower'''<ref>{{cite book |last=Hofstadter |first=Douglas R. |title=Metamagical Themas : Questing for the Essence of Mind and Pattern |url=https://archive.org/details/metamagicalthema0000hofs |url-access=registration |year=1985 |publisher=Basic Books |location=New York |isbn=978-0-465-04540-2}}</ref> and sometimes pluralized as '''Towers''', or simply '''pyramid puzzle'''<ref>{{cite journal |journal=The Mathematics Teacher |date=1963 |volume=56 |page=84 |url=https://books.google.com/books?id=edoVAAAAIAAJ&q=tower+hanoi+pyramid+puzzle |access-date=9 March 2021 |publisher=National Council of Teachers of Mathematics |doi=10.5951/MT.56.2.0084 |issn=0025-5769|title=A device for demonstrating some elementary properties of integers |last=Cohn |first=Ernst M. |issue=2 }}</ref>) is a [[mathematical game]] or [[puzzle]] consisting of three rods and a number of disks of various [[diameter]]s, which can slide onto any rod. The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top, thus approximating a [[conical]] shape. The objective of the puzzle is to move the entire stack to one of the other rods, obeying the following rules:<ref>{{Cite web |last=Weisstein |first=Eric W. |title=Tower of Hanoi |url=https://mathworld.wolfram.com/ |access-date=2023-10-20 |website=mathworld.wolfram.com |language=en}}</ref>


# Only one disk may be moved at a time.
# Only one disk may be moved at a time.
Line 10: Line 12:
# No disk may be placed on top of a disk that is smaller than it.
# No disk may be placed on top of a disk that is smaller than it.


With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2<sup>''n''</sup> − 1, where ''n'' is the number of disks.
With three disks, the puzzle can be solved in seven moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is {{nowrap|2<sup>''n''</sup> − 1}}, where ''n'' is the number of disks.


== Origins ==
== Origins ==
The puzzle was invented by the [[French people|French]] [[mathematician]] [[Édouard Lucas]] in 1883. Numerous myths regarding the ancient and mystical nature of the puzzle popped up almost immediately,<ref>{{cite book | title=The Tower of Hanoi – Myths and Maths|title-link= The Tower of Hanoi – Myths and Maths | isbn= 978-3034802369| last1= Hinz| first1= Andreas M.| last2= Klavžar| first2= Sandi| last3= Milutinović| first3= Uroš| last4= Petr| first4= Ciril| date= 2013-01-31}}</ref> including one about an [[India]]n temple in [[Kashi Vishwanath Temple|Kashi Vishwanath]] containing a large room with three time-worn posts in it, surrounded by 64 golden disks. Acting out the command of an ancient prophecy, [[Brahmin]] priests have been moving these disks in accordance with the immutable rules of Brahma since that time. The puzzle is therefore also known as the Tower of [[Brahma]]. According to the legend, when the last move of the puzzle is completed, the world will end.<ref>{{cite book |last=Spitznagel |first=Edward L. |title=Selected topics in mathematics |year=1971 |publisher=Holt, Rinehart and Winston |page=[https://archive.org/details/selectedtopicsin0000spit/page/137 137] |isbn=978-0-03-084693-9 |url-access=registration |url=https://archive.org/details/selectedtopicsin0000spit/page/137 }}</ref>
The puzzle was invented by the French [[mathematician]] [[Édouard Lucas]], first presented in 1883 as a game discovered by "N. Claus (de Siam)" (an anagram of "Lucas d'Amiens"),<ref name="hinz13">{{cite book | title=The Tower of Hanoi – Myths and Maths|title-link= The Tower of Hanoi – Myths and Maths | isbn= 978-3034802369| last1= Hinz| first1= Andreas M.| last2= Klavžar| first2= Sandi| last3= Milutinović| first3= Uroš| last4= Petr| first4= Ciril| date= 2013-01-31|publisher= Springer }}</ref><ref name="stockmeyer05">{{cite web |last1=Stockmeyer |first1=Paul K. |title=The Tower of Hanoi: A Bibliography |url=https://www.cs.wm.edu/~pkstoc/biblio2.pdf |access-date=2024-02-21}}</ref><ref name="parville83">{{cite news |last1=de Parville |first1=Henri |title=Revue des Sciences |url=https://gallica.bnf.fr/ark:/12148/bpt6k462461g/f2.item.zoom |access-date=2024-02-21 |work=Journal des débats |date=1883-12-27}}</ref> and later published as a booklet in 1889<ref>{{cite book | first = Édouard | last = Lucas | author-link = Édouard Lucas | title = Jeux scientifiques pour servir à l'histoire, à l'enseignement et à la pratique du calcul et du dessin | publisher = Chambon et Baye | date = 1889| language = fr | location = Paris | url = https://gallica.bnf.fr/ark:/12148/bpt6k3943s/f272 | access-date = 2024-01-27}}</ref> and in a posthumously-published volume of Lucas' ''Récréations mathématiques''.<ref>{{ cite book | first = Édouard | last = Lucas | author-link = Édouard Lucas | title = Récréations mathématiques | volume = 3 | year = 1892 | language = fr | publisher = Librairie Albert Blanchard, 1979 | page = 58 | url = https://gallica.bnf.fr/ark:/12148/bpt6k3945d/f64}}</ref> Accompanying the game was an instruction booklet, describing the game's purported origins in [[Tonkin]], and claiming that according to legend [[Brahmins]] at a temple in [[Benares]] have been carrying out the movement of the "Sacred Tower of [[Brahma]]", consisting of sixty-four golden disks, according to the same rules as in the game, and that the completion of the tower would lead to the end of the world.<ref name="stockmeyerinst">{{cite web |last1=Stockmeyer |first1=Paul K. |title=Tower of Hanoi instructions in English, page 1 |url=https://www.cs.wm.edu/~pkstoc/page_1.html|access-date=2024-02-21}}</ref> Numerous variations on this legend regarding the ancient and mystical nature of the puzzle popped up almost immediately.<ref name="hinz13" />


If the legend was 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 2<sup>64</sup>&nbsp;−&nbsp;1 seconds or roughly 585 [[1,000,000,000|billion]] years to finish,<ref>{{cite book |last=Moscovich |first=Ivan |author-link=Ivan Moscovich |title=1000 playthinks: puzzles, paradoxes, illusions & games |publisher=Workman |year=2001 |isbn=978-0-7611-1826-8 }}</ref> which is about 42 times the current age of the universe.
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 2<sup>64</sup>&nbsp;−&nbsp;1 seconds or roughly 585 [[1,000,000,000|billion]] years to finish,<ref>{{cite book |last=Moscovich |first=Ivan |author-link=Ivan Moscovich |title=1000 playthinks: puzzles, paradoxes, illusions & games |publisher=Workman |year=2001 |isbn=978-0-7611-1826-8 }}</ref> which is about 42 times the estimated current [[age of the universe]].


There are many variations on this legend. For instance, in some tellings, the temple is a [[monastery]], and the priests are [[monk]]s. The temple or monastery may in various locales including [[Hanoi]], 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.
There are many variations on this legend. For instance, in some tellings, the temple is a [[monastery]], and the priests are [[monk]]s. The temple or monastery may be in various locales including [[Hanoi]], 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.


== Solution ==
== Solution ==
The puzzle can be played with any number of disks, although many toy versions have around 7 to 9 of them. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2<sup>''n''</sup> − 1, where ''n'' is the number of disks.<ref>{{cite book |last=Petković |first=Miodrag |title=Famous Puzzles of Great Mathematicians |year=2009 |publisher=AMS Bookstore |isbn=978-0-8218-4814-2 |page=197}}</ref>
The puzzle can be played with any number of disks, although many toy versions have around 7 to 9 of them. The minimal number of moves required to solve a Tower of Hanoi puzzle with ''n'' disks is {{nowrap|2<sup>''n''</sup> − 1}}.<ref>{{cite book |last=Petković |first=Miodrag |title=Famous Puzzles of Great Mathematicians |year=2009 |publisher=AMS Bookstore |isbn=978-0-8218-4814-2 |page=197}}</ref>


=== Iterative solution ===
=== Iterative solution ===
[[File:Iterative algorithm solving a 6 disks Tower of Hanoi.gif|thumb|Animation of an iterative algorithm solving 6-disk problem]]
[[File:Iterative algorithm solving a 6 disks Tower of Hanoi.gif|thumb|Animation of an iterative algorithm-solving 6-disk problem]]
A simple solution for the toy puzzle is to alternate moves between the smallest piece and a non-smallest piece. When moving the smallest piece, always move it to the next position 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 position 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 in the fewest moves.<ref>{{cite journal |last=Troshkin |first=M. |title=Doomsday Comes: A Nonrecursive Analysis of the Recursive Towers-of-Hanoi Problem |journal=Focus |volume=95 |issue=2 |pages=10–14 |language=ru }}</ref>
A simple solution for the toy puzzle is to alternate moves between the smallest piece and a non-smallest piece. When moving the smallest piece, always move it to the next position 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 position 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 in the fewest moves.<ref>{{cite journal |last=Troshkin |first=M. |title=Doomsday Comes: A Nonrecursive Analysis of the Recursive Towers-of-Hanoi Problem |journal=Focus |volume=95 |issue=2 |pages=10–14 |language=ru }}</ref>


==== Simpler statement of iterative solution ====
==== Simpler statement of iterative solution ====
{{More citations needed section|date=January 2024}}
For an even number of disks:
The iterative solution is equivalent to repeated execution of the following sequence of steps until the goal has been achieved:
* make the legal move between pegs A and B (in either direction),
* Move one disk from peg A to peg B or vice versa, whichever move is legal.
* make the legal move between pegs A and C (in either direction),
* Move one disk from peg A to peg C or vice versa, whichever move is legal.
* make the legal move between pegs B and C (in either direction),
* Move one disk from peg B to peg C or vice versa, whichever move is legal.
* repeat until complete.
Following this approach, the stack will end up on peg B if the number of disks is odd and peg C if it is even.

For an odd number of disks:
* make the legal move between pegs A and C (in either direction),
* make the legal move between pegs A and B (in either direction),
* make the legal move between pegs B and C (in either direction),
* repeat until complete.

In each case, a total of 2<sup>n</sup> − 1 moves are made.

==== Equivalent iterative solution ====
Another way to generate the unique optimal iterative solution:

Number the disks 1 through ''n'' (largest to smallest).
* If ''n'' is odd, the first move is from peg A to peg C.
* If ''n'' is even, the first move is from peg A to peg B.

Now, add these constraints:
* No odd disk may be placed directly on an odd disk.
* No even disk may be placed directly on an even disk.
* There will sometimes be two possible pegs: one will have disks, and the other will be empty. Place the disk on the non-empty peg.
* Never move a disk twice in succession.

Considering those constraints after the first move, there is only one legal move at every subsequent turn.

The sequence of these unique moves is an optimal solution to the problem equivalent to the iterative solution described above.<ref>{{cite journal |first1=Herbert |last1=Mayer |first2=Don |last2=Perkins |title=Towers of Hanoi Revisited |pages=80–84 |journal=SIGPLAN Notices |year=1984 |doi=10.1145/948566.948573 |volume=19|issue=2 |s2cid=2304761 }}</ref>


=== Recursive solution ===
=== Recursive solution ===
{{More citations needed section|date=January 2024}}
[[File:Tower of Hanoi recursion SMIL.svg|thumb|Illustration of a recursive solution for the Towers of Hanoi puzzle with 4 disks]]
[[File:Tower of Hanoi recursion SMIL.svg|thumb|link={{filepath:Tower_of_Hanoi_recursion_SMIL.svg}}|Illustration of a recursive solution for the Towers of Hanoi puzzle with 4 disks. In [{{filepath:Tower_of_Hanoi_recursion_SMIL.svg}} the SVG file,] click a grey button to expand or collapse it]]
The key to solving a problem recursively is to recognize that it can be broken down into a collection of smaller sub-problems, to each of which ''that same general solving procedure that we are seeking'' applies, and the total solution is then found in some ''simple'' way from those sub-problems' solutions. Each of these created sub-problems being "smaller" guarantees that the base case(s) will eventually be reached. Thence, for the Towers of Hanoi:
The key to solving a problem [[recursive]]ly is to recognize that it can be broken down into a collection of smaller sub-problems, to each of which ''that same general solving procedure that we are seeking'' applies{{Citation needed|date=January 2024}}, and the total solution is then found in some ''simple'' way from those sub-problems' solutions. Each of these created sub-problems being "smaller" guarantees that the base case(s) will eventually be reached. For the Towers of Hanoi:
* label the pegs A, B, C,
* label the pegs A, B, C,
* let ''n'' be the total number of disks,
* let ''n'' be the total number of disks, and
* number the disks from 1 (smallest, topmost) to ''n'' (largest, bottom-most).
* number the disks from 1 (smallest, topmost) to ''n'' (largest, bottom-most).


Line 68: Line 47:
# Move ''m'' − 1 disks from the '''source''' to the '''spare''' peg, by ''the same general solving procedure''. Rules are not violated, by assumption. This leaves the disk ''m'' as a top disk on the source peg.
# Move ''m'' − 1 disks from the '''source''' to the '''spare''' peg, by ''the same general solving procedure''. Rules are not violated, by assumption. This leaves the disk ''m'' as a top disk on the source peg.
# Move the disk ''m'' from the '''source''' to the '''target''' peg, which is guaranteed to be a valid move, by the assumptions — ''a simple step''.
# Move the disk ''m'' from the '''source''' to the '''target''' peg, which is guaranteed to be a valid move, by the assumptions — ''a simple step''.
# Move the ''m'' − 1 disks that we have just placed on the spare, from the '''spare''' to the '''target''' peg by ''the same general solving procedure'', so they are placed on top of the disk ''m'' without violating the rules.
# Move the ''m'' − 1 disk that we have just placed on the spare, from the '''spare''' to the '''target''' peg by ''the same general solving procedure'', so they are placed on top of the disk ''m'' without violating the rules.
# The base case is to move ''0'' disks (in steps 1 and 3), that is, do nothing &ndash; which obviously doesn't violate the rules.
# The base case is to move ''0'' disks (in steps 1 and 3), that is, do nothing—which does not violate the rules.


The full Tower of Hanoi solution then consists of moving ''n'' disks from the source peg A to the target peg C, using B as the spare peg.
The full Tower of Hanoi solution then moves ''n'' disks from the source peg A to the target peg C, using B as the spare peg.


This approach can be given a rigorous mathematical proof with [[mathematical induction]] and is often used as an example of recursion when teaching programming.
This approach can be given a rigorous mathematical proof with [[mathematical induction]] and is often used as an example of recursion when teaching programming.


==== Logical analysis of the recursive solution ====
==== Logical analysis of the recursive solution ====
{{More citations needed section|date=January 2024}}
<!-- TODO: This section needs copy-editing for tone, professionalism and clarity: edited/bolded .-->
<!-- TODO: This section needs copy-editing for tone, professionalism and clarity: edited/bolded .-->
As in many mathematical puzzles, finding a solution is made easier by solving a slightly more general problem: how to move a tower of ''h'' (height) disks from a starting peg ''f'' = '''A''' (from) onto a destination peg ''t'' = '''C''' (to), '''B''' being the remaining third peg and assuming ''t'' ≠ ''f''. First, observe that the problem is symmetric for permutations of the names of the pegs ([[Symmetric group|symmetric group ''S''<sub>3</sub>]]). If a solution is known moving from peg '''A''' to peg '''C''', then, by renaming the pegs, the same solution can be used for every other choice of starting and destination peg. If there is only one disk (or even none at all), the problem is trivial. If ''h'' = 1, then simply move the disk from peg '''A''' to peg '''C'''. If ''h'' > 1, then somewhere along the sequence of moves, the largest disk must be moved from peg '''A''' to another peg, preferably to peg '''C'''. The only situation that allows this move is when all smaller ''h'' − 1 disks are on peg '''B'''. Hence, first all ''h'' − 1 smaller disks must go from '''A''' to '''B'''. Then move the largest disk and finally move the ''h'' − 1 smaller disks from peg '''B''' to peg '''C'''. The presence of the largest disk does not impede any move of the ''h'' − 1 smaller disks and can be temporarily ignored. Now the problem is reduced to moving ''h'' − 1 disks from one peg to another one, first from '''A''' to '''B''' and subsequently from '''B''' to '''C''', but the same method can be used both times by renaming the pegs. The same strategy can be used to reduce the ''h'' − 1 problem to ''h'' − 2, ''h'' − 3, and so on until only one disk is left. This is called recursion. This algorithm can be schematized as follows.
As in many mathematical puzzles, finding a solution is made easier by solving a slightly more general problem: how to move a tower of ''h'' (height) disks from a starting peg ''f'' = '''A''' (from) onto a destination peg ''t'' = '''C''' (to), '''B''' being the remaining third peg and assuming ''t'' ≠ ''f''. First, observe that the problem is symmetric for permutations of the names of the pegs ([[Symmetric group|symmetric group ''S''<sub>3</sub>]]). If a solution is known moving from peg '''A''' to peg '''C''', then, by renaming the pegs, the same solution can be used for every other choice of starting and destination peg. If there is only one disk (or even none at all), the problem is trivial. If ''h'' = 1, then move the disk from peg '''A''' to peg '''C'''. If ''h'' > 1, then somewhere along the sequence of moves, the largest disk must be moved from peg '''A''' to another peg, preferably to peg '''C'''. The only situation that allows this move is when all smaller ''h'' − 1 disks are on peg '''B'''. Hence, first all ''h'' − 1 smaller disks must go from '''A''' to '''B'''. Then move the largest disk and finally move the ''h'' − 1 smaller disks from peg '''B''' to peg '''C'''. The presence of the largest disk does not impede any move of the ''h'' − 1 smaller disks and can be temporarily ignored. Now the problem is reduced to moving ''h'' − 1 disks from one peg to another one, first from '''A''' to '''B''' and subsequently from '''B''' to '''C''', but the same method can be used both times by renaming the pegs. The same strategy can be used to reduce the ''h'' − 1 problem to ''h'' − 2, ''h'' − 3, and so on until only one disk is left. This is called recursion. This algorithm can be schematized as follows.


Identify the disks in order of increasing size by the natural numbers from 0 up to but not including ''h''. Hence disk 0 is the smallest one, and disk ''h'' − 1 the largest one.
Identify the disks in order of increasing size by the natural numbers from 0 up to but not including ''h''. Hence disk 0 is the smallest one, and disk ''h'' − 1 the largest one.
Line 86: Line 66:
# If ''h'' > 1, then again use this procedure to move the ''h'' − 1 smaller disks from peg '''B''' to peg '''C'''.
# If ''h'' > 1, then again use this procedure to move the ''h'' − 1 smaller disks from peg '''B''' to peg '''C'''.


By means of [[mathematical induction]], it is easily proven that the above procedure requires the minimal number of moves possible and that the produced solution is the only one with this minimal number of moves. Using [[recurrence relation]]s, the exact number of moves that this solution requires can be calculated by: <math>2^h - 1</math>. This result is obtained by noting that steps 1 and 3 take <math>T_{h-1}</math> moves, and step 2 takes one move, giving <math>T_h = 2T_{h-1} + 1</math>.
By [[mathematical induction]], it is easily proven that the above procedure requires the minimum number of moves possible and that the produced solution is the only one with this minimal number of moves. Using [[recurrence relation]]s, the exact number of moves that this solution requires can be calculated by: <math>2^h - 1</math>. This result is obtained by noting that steps 1 and 3 take <math>T_{h-1}</math> moves, and step 2 takes one move, giving <math>T_h = 2T_{h-1} + 1</math>.


==== Recursive implementation ====
==== Non-recursive solution ====
{{More citations needed section|date=January 2024}}
The following [[Python (programming language)|Python]] code highlights an essential function of the recursive solution, which may be otherwise misunderstood or overlooked. That is, with every level of recursion, the first recursive call inverts the ''target'' and ''auxiliary'' stacks, while in the second recursive call the ''source'' and ''auxiliary'' stacks are inverted.

<syntaxhighlight lang="python">
A = [3, 2, 1]
B = []
C = []

def move(n, source, target, auxiliary):
if n > 0:
# Move n - 1 disks from source to auxiliary, so they are out of the way
move(n - 1, source, auxiliary, target)

# Move the nth disk from source to target
target.append(source.pop())

# Display our progress
print(A, B, C, '##############', sep='\n')

# Move the n - 1 disks that we left on auxiliary onto target
move(n - 1, auxiliary, target, source)

# Initiate call from source A to target C with auxiliary B
move(3, A, C, B)
</syntaxhighlight>

=== Non-recursive solution ===
The list of moves for a tower being carried from one peg onto another one, as produced by the recursive algorithm, has many regularities. When counting the moves starting from 1, the ordinal of the disk to be moved during move ''m'' is the number of times ''m'' can be divided by 2. Hence every odd move involves the smallest disk. It can also be observed that the smallest disk traverses the pegs ''f'', ''t'', ''r'', ''f'', ''t'', ''r'', etc. for odd height of the tower and traverses the pegs ''f'', ''r'', ''t'', ''f'', ''r'', ''t'', etc. for even height of the tower. This provides the following algorithm, which is easier, carried out by hand, than the recursive algorithm.
The list of moves for a tower being carried from one peg onto another one, as produced by the recursive algorithm, has many regularities. When counting the moves starting from 1, the ordinal of the disk to be moved during move ''m'' is the number of times ''m'' can be divided by 2. Hence every odd move involves the smallest disk. It can also be observed that the smallest disk traverses the pegs ''f'', ''t'', ''r'', ''f'', ''t'', ''r'', etc. for odd height of the tower and traverses the pegs ''f'', ''r'', ''t'', ''f'', ''r'', ''t'', etc. for even height of the tower. This provides the following algorithm, which is easier, carried out by hand, than the recursive algorithm.


Line 135: Line 90:


=== Binary solution ===
=== Binary solution ===
{{More citations needed section|date=January 2024}}
Disk positions may be determined more directly from the [[binary numeral system|binary]] (base-2) representation of the move number (the initial state being move #0, with all digits 0, and the final state being with all digits 1), using the following rules:
Disk positions may be determined more directly from the [[binary numeral system|binary]] (base-2) representation of the move number (the initial state being move #0, with all digits 0, and the final state being with all digits 1), using the following rules:
* There is one binary digit ([[bit]]) for each disk.
* There is one binary digit ([[bit]]) for each disk.
* The most significant (leftmost) bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it's on the final peg (right peg if number of disks is odd and middle peg otherwise).
* The [[Most significant bit|most significant (leftmost) bit]] represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it is on the final peg (right peg if number of disks is odd and middle peg otherwise).
* The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk.
* The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk.
* A bit with the same value as the previous one means that the corresponding disk is stacked on top of the previous disk on the same peg.
* A bit with the same value as the previous one means that the corresponding disk is stacked on top of the previous disk on the same peg.
Line 143: Line 99:
* A bit with a different value to the previous one means that the corresponding disk is one position to the left or right of the previous one. Whether it is left or right is determined by this rule:
* A bit with a different value to the previous one means that the corresponding disk is one position to the left or right of the previous one. Whether it is left or right is determined by this rule:
** Assume that the initial peg is on the left.
** Assume that the initial peg is on the left.
** Also assume "wrapping" – so the right peg counts as one peg "left" of the left peg, and vice versa.
** Also assume "wrapping"—so the right peg counts as one peg "left" of the left peg, and vice versa.
** Let ''n'' be the number of greater disks that are located on the same peg as their first greater disk and add 1 if the largest disk is on the left peg. If ''n'' is even, the disk is located one peg to the right, if ''n'' is odd, the disk located one peg to the left (in case of even number of disks and vice versa otherwise).
** Let ''n'' be the number of greater disks that are located on the same peg as their first greater disk and add 1 if the largest disk is on the left peg. If ''n'' is even, the disk is located one peg to the right, if ''n'' is odd, the disk located one peg to the left (in case of an even number of disks and vice versa otherwise).


For example, in an 8-disk Hanoi:
For example, in an 8-disk Hanoi:
Line 150: Line 106:
** The largest disk is 0, so it is on the left (initial) peg.
** The largest disk is 0, so it is on the left (initial) peg.
** All other disks are 0 as well, so they are stacked on top of it. Hence all disks are on the initial peg.
** All other disks are 0 as well, so they are stacked on top of it. Hence all disks are on the initial peg.
* Move 2<sup>8</sup> − 1 = 11111111.
* Move {{nowrap|2<sup>8</sup> − 1}} = 11111111.
** The largest disk is 1, so it is on the middle (final) peg.
** The largest disk is 1, so it is on the middle (final) peg.
** All other disks are 1 as well, so they are stacked on top of it. Hence all disks are on the final peg and the puzzle is complete.
** All other disks are 1 as well, so they are stacked on top of it. Hence all disks are on the final peg and the puzzle is complete.
Line 162: Line 118:
** Disks seven and eight are also 0, so they are stacked on top of it, on the left peg.
** Disks seven and eight are also 0, so they are stacked on top of it, on the left peg.


The source and destination pegs for the ''m''th move can also be found elegantly from the binary representation of ''m'' using [[bitwise operation]]s. To use the syntax of the [[C (programming language)|C programming language]], move ''m'' is from peg <code>(m & m - 1) % 3</code> to peg <code>((m | m - 1) + 1) % 3</code>, where the disks begin on peg 0 and finish on peg 1 or 2 according as whether the number of disks is even or odd. Another formulation is from peg <code>(m - (m & -m)) % 3</code> to peg <code>(m + (m & -m)) % 3</code>.
The source and destination pegs for the ''m''th move can also be found elegantly from the binary representation of ''m'' using [[bitwise operation]]s. To use the syntax of the [[C programming language]], move ''m'' is from peg <code>(m & m - 1) % 3</code> to peg <code>((m | m - 1) + 1) % 3</code>, where the disks begin on peg 0 and finish on peg 1 or 2 according as whether the number of disks is even or odd. Another formulation is from peg <code>(m - (m & -m)) % 3</code> to peg <code>(m + (m & -m)) % 3</code>.


Furthermore, the disk to be moved is determined by the number of times the move count (''m'') can be divided by 2 (i.e. the number of zero bits at the right), counting the first move as 1 and identifying the disks by the numbers 0, 1, 2, etc. in order of increasing size. This permits a very fast non-recursive computer implementation to find the positions of the disks after m moves without reference to any previous move or distribution of disks.
Furthermore, the disk to be moved is determined by the number of times the move count (''m'') can be divided by 2 (i.e. the number of zero bits at the right), counting the first move as 1 and identifying the disks by the numbers 0, 1, 2, etc. in order of increasing size. This permits a very fast non-recursive computer implementation to find the positions of the disks after m moves without reference to any previous move or distribution of disks.


The operation, which counts the number of consecutive zeros at the end of a binary number, gives a simple solution to the problem: the disks are numbered from zero, and at move ''m'', disk number [[count trailing zeros]] is moved the minimal possible distance to the right (circling back around to the left as needed).<ref>{{cite book |last=Warren |first=Henry S. |title=Hacker's delight |year=2003 |publisher=Addison-Wesley |location=Boston MA |isbn=978-0-201-91465-8 |edition=1st |chapter=Section 5-4: Counting Trailing 0's.}}</ref>
The operation, which counts the number of consecutive zeros at the end of a binary number, gives a simple solution to the problem: the disks are numbered from zero, and at move ''m'', disk number [[count trailing zeros]] is moved the minimal possible distance to the right (circling back around to the left as needed).<ref>{{cite book |last=Warren |first=Henry S. |title=Hacker's delight |year=2003 |publisher=Addison-Wesley |location=Boston MA |isbn=978-0-201-91465-8 |edition=1st |chapter=Section 5-4: Counting Trailing 0's.}}</ref>


=== Gray-code solution ===
=== Gray-code solution ===
{{More citations needed section|date=January 2024}}
The binary numeral system of [[Gray code]]s gives an alternative way of solving the puzzle. In the Gray system, numbers are expressed in a binary combination of 0s and 1s, but rather than being a standard [[numeral system|positional numeral system]], Gray code operates on the premise that each value differs from its predecessor by only one (and exactly one) bit changed.
The binary numeral system of [[Gray code]]s gives an alternative way of solving the puzzle. In the Gray system, numbers are expressed in a binary combination of 0s and 1s, but rather than being a standard [[positional numeral system]], the Gray code operates on the premise that each value differs from its predecessor by only one bit changed.


If one counts in Gray code of a bit size equal to the number of disks in a particular Tower of Hanoi, begins at zero and counts up, then the bit changed each move corresponds to the disk to move, where the least-significant bit is the smallest disk, and the most-significant bit is the largest.
If one counts in Gray code of a bit size equal to the number of disks in a particular Tower of Hanoi, begins at zero and counts up, then the bit changed each move corresponds to the disk to move, where the least-significant bit is the smallest disk, and the most-significant bit is the largest.
Line 175: Line 132:
:Counting moves from 1 and identifying the disks by numbers starting from 0 in order of increasing size, the ordinal of the disk to be moved during move ''m'' is the number of times ''m'' can be divided by 2.
:Counting moves from 1 and identifying the disks by numbers starting from 0 in order of increasing size, the ordinal of the disk to be moved during move ''m'' is the number of times ''m'' can be divided by 2.


This technique identifies which disk to move, but not where to move it to. For the smallest disk, there are always two possibilities. For the other disks there is always one possibility, except when all disks are on the same peg, but in that case either it is the smallest disk that must be moved or the objective has already been achieved. Luckily, there is a rule that does say where to move the smallest disk to. Let ''f'' be the starting peg, ''t'' the destination peg, and ''r'' the remaining third peg. If the number of disks is odd, the smallest disk cycles along the pegs in the order ''f'' → ''t'' → ''r'' → ''f'' → ''t'' → ''r'', etc. If the number of disks is even, this must be reversed: ''f'' → ''r'' → ''t'' → ''f'' → ''r'' → ''t'', etc.<ref>{{cite book |first=Charles D. |last=Miller |chapter=Ch. 4: Binary Numbers and the Standard Gray Code |chapter-url=https://web.archive.org/web/20040821062630/http://occawlonline.pearsoned.com/bookbind/pubbooks/miller2_awl/chapter4/essay1/deluxe-content.html#tower |title=Mathematical Ideas |edition=9 |publisher=Addison Wesley Longman |year=2000 |isbn=978-0-321-07607-6 |url-status=bot: unknown |archive-url=https://web.archive.org/web/20040821062630/http://occawlonline.pearsoned.com/bookbind/pubbooks/miller2_awl/chapter4/essay1/deluxe-content.html#tower |archive-date=2004-08-21 |url=http://occawlonline.pearsoned.com/bookbind/pubbooks/miller2_awl/chapter4/essay1/deluxe-content.html }}</ref>
This technique identifies which disk to move, but not where to move it to. For the smallest disk, there are always two possibilities. For the other disks there is always one possibility, except when all disks are on the same peg, but in that case either it is the smallest disk that must be moved or the objective has already been achieved. Luckily, there is a rule that does say where to move the smallest disk to. Let ''f'' be the starting peg, ''t'' the destination peg, and ''r'' the remaining third peg. If the number of disks is odd, the smallest disk cycles along the pegs in the order ''f'' → ''t'' → ''r'' → ''f'' → ''t'' → ''r'', etc. If the number of disks is even, this must be reversed: ''f'' → ''r'' → ''t'' → ''f'' → ''r'' → ''t'', etc.<ref>{{cite book |first=Charles D. |last=Miller |title=Mathematical Ideas |chapter=Ch. 4: Binary Numbers and the Standard Gray Code |edition=9 |publisher=Addison Wesley Longman |year=2000 |isbn=978-0-321-07607-6 |url-status=dead |archive-url=https://web.archive.org/web/20040821062630/http://occawlonline.pearsoned.com/bookbind/pubbooks/miller2_awl/chapter4/essay1/deluxe-content.html#tower |archive-date=2004-08-21 |url=http://occawlonline.pearsoned.com/bookbind/pubbooks/miller2_awl/chapter4/essay1/deluxe-content.html }}</ref>


The position of the bit change in the Gray code solution gives the size of the disk moved at each step: 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, ... {{OEIS|id=A001511}},<ref>{{Cite book|title=Théorie du Baguenodier|last=Gros|first=L.|publisher=Aimé Vingtrinier|year=1872|location=Lyon}}</ref> a sequence also known as the [[ruler function]], or one more than the power of 2 within the move number. In the [[Wolfram Language]], <code>IntegerExponent[Range[2^8 - 1], 2] + 1</code> gives moves for the 8-disk puzzle.
The position of the bit change in the Gray code solution gives the size of the disk moved at each step: 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, ... {{OEIS|id=A001511}},<ref>{{Cite book|title=Théorie du Baguenodier|last=Gros|first=L.|publisher=Aimé Vingtrinier|year=1872|location=Lyon}}</ref> a sequence also known as the [[ruler function]], or one more than the power of 2 within the move number. In the [[Wolfram Language]], <code>IntegerExponent[Range[2^8 - 1], 2] + 1</code> gives moves for the 8-disk puzzle.
Line 181: Line 138:
== Graphical representation ==
== Graphical representation ==
{{main|Hanoi graph}}
{{main|Hanoi graph}}

The game can be represented by an [[Graph (discrete mathematics)#Undirected graph|undirected graph]], the nodes representing distributions of disks and the edges representing moves. For one disk, the graph is a triangle:
The game can be represented by an [[Graph (discrete mathematics)#Undirected graph|undirected graph]], the nodes representing distributions of disks and the edges representing moves. For one disk, the graph is a triangle:


[[file:tower_of_hanoi_graph.svg|lang=simple|120px|center]]
[[file:tower_of_hanoi_graph.svg|lang=en-simple|120px|center]]


The graph for two disks is three triangles connected to form the corners of a larger triangle.
The graph for two disks is three triangles connected to form the corners of a larger triangle.
Line 223: Line 181:
* From every arbitrary distribution of disks, there is exactly one shortest way to move all disks onto one of the three pegs.
* From every arbitrary distribution of disks, there is exactly one shortest way to move all disks onto one of the three pegs.
* Between every pair of arbitrary distributions of disks there are one or two different shortest paths.
* Between every pair of arbitrary distributions of disks there are one or two different shortest paths.
* From every arbitrary distribution of disks, there are one or two different longest non selfcrossing paths to move all disks to one of the three pegs.
* From every arbitrary distribution of disks, there are one or two different longest non-self-crossing paths to move all disks to one of the three pegs.
* Between every pair of arbitrary distributions of disks there are one or two different longest non self-crossing paths.
* Between every pair of arbitrary distributions of disks there are one or two different longest non-self-crossing paths.
* Let ''N''<sub>''h''</sub> be the number of non-self-crossing paths for moving a tower of ''h'' disks from one peg to another one. Then:
* Let ''N''<sub>''h''</sub> be the number of non-self-crossing paths for moving a tower of ''h'' disks from one peg to another one. Then:
** ''N''<sub>1</sub> = 2
** ''N''<sub>1</sub> = 2
Line 231: Line 189:


== Variations ==
== Variations ==
=== Adjacent pegs ===
=== Linear Hanoi ===
If all moves must be between adjacent pegs (i.e. given pegs A, B, C, one cannot move directly between pegs A and C), then moving a stack of ''n'' disks from peg A to peg C takes 3<sup>''n''</sup> − 1 moves. The solution uses all 3<sup>n</sup> valid positions, always taking the unique move that does not undo the previous move. The position with all disks at peg B is reached halfway, i.e. after (3<sup>''n''</sup> − 1) / 2 moves.{{citation needed|date=June 2019}}
If all moves must be between adjacent pegs (i.e. given pegs A, B, C, one cannot move directly between pegs A and C), then moving a stack of ''n'' disks from peg A to peg C takes 3<sup>''n''</sup> − 1 moves. The solution uses all 3<sup>n</sup> valid positions, always taking the unique move that does not undo the previous move. The position with all disks at peg B is reached halfway, i.e. after (3<sup>''n''</sup> − 1) / 2 moves.<ref>{{Cite web |title=Question Corner -- Generalizing the Towers of Hanoi Problem |url=https://www.math.toronto.edu/mathnet/questionCorner/genhanoi.html |access-date=2023-07-28 |website=math.toronto.edu}}</ref><ref>{{Cite book |last1=Hinz |first1=Andreas M. |title=The Tower of Hanoi – Myths and Maths |last2=Klavzar |first2=Sandi |last3=Milutinovic |first3=Uros |last4=Petr |first4=Ciril |last5=Stewart |first5=Ian |publisher=[[Springer Science+Business Media]] |year=2013 |isbn=9783034802369 |edition=1st |location=Basel |pages=241–259 |language=en}}</ref>


=== Cyclic Hanoi ===
=== Cyclic Hanoi ===
In Cyclic Hanoi, we are given three pegs (A, B, C), which are arranged as a circle with the clockwise and the counterclockwise directions being defined as A – B – C – A and A – C – B – A respectively. The moving direction of the disk must be clockwise.<ref>{{cite journal |first=T. D. |last=Gedeon |title=The Cyclic Towers of Hanoi: An Iterative Solution Produced by Transformation |journal=The Computer Journal |volume=39 |issue=4 |year=1996 |doi=10.1093/comjnl/39.4.353 |pages=353–356}}</ref> It suffices to represent the sequence of disks to be moved. The solution can be found using two mutually recursive procedures:
In Cyclic Hanoi, we are given three pegs (A, B, C), which are arranged as a circle with the clockwise and the counterclockwise directions being defined as A – B – C – A and A – C – B – A, respectively. The moving direction of the disk must be clockwise.<ref>{{cite journal |first=T. D. |last=Gedeon |title=The Cyclic Towers of Hanoi: An Iterative Solution Produced by Transformation |journal=The Computer Journal |volume=39 |issue=4 |year=1996 |doi=10.1093/comjnl/39.4.353 |pages=353–356}}</ref> It suffices to represent the sequence of disks to be moved. The solution can be found using two mutually recursive procedures:


To move ''n'' disks '''counterclockwise''' to the neighbouring target peg:
To move ''n'' disks '''counterclockwise''' to the neighbouring target peg:
Line 252: Line 210:


Let C(n) and A(n) represent moving n disks clockwise and counterclockwise, then we can write down both formulas:
Let C(n) and A(n) represent moving n disks clockwise and counterclockwise, then we can write down both formulas:
{|

C(n) = A(n-1) n A(n-1) and A(n) = A(n-1) n C(n-1) n A(n-1).
| || {{nowrap|1=C(n) = A(n−1) n A(n−1)}} || and || {{nowrap|1=A(n) = A(n−1) n C(n−1) n A(n−1).}}
|-

| style="padding:1ex 3ex;"|
Thus C(1) = 1 and A(1) = 1 1,
|-
C(2) = 1 1 2 1 1 and A(2) = 1 1 2 1 2 1 1.
| Thus || C(1) = 1 || and || A(1) = 1 1,

|-
| || C(2) = 1 1 2 1 1 || and || A(2) = 1 1 2 1 2 1 1.
|}
The solution for the Cyclic Hanoi has some interesting properties:
The solution for the Cyclic Hanoi has some interesting properties:


1)The move-patterns of transferring a tower of disks from a peg to another peg are symmetric with respect to the center points.
# The move-patterns of transferring a tower of disks from a peg to another peg are symmetric with respect to the center points.
# The smallest disk is the first and last disk to move.

2)The smallest disk is the first and last disk to move.
# Groups of the smallest disk moves alternate with single moves of other disks.
# The number of disks moves specified by C(n) and A(n) are minimal.

3)Groups of the smallest disk moves alternate with single moves of other disks.

4)The number of disks moves specified by C(n) and A(n) are minimal.


=== With four pegs and beyond ===
=== With four pegs and beyond ===
Although the three-peg version has a simple recursive solution long been known, the optimal solution for the Tower of Hanoi problem with four pegs (called Reve's puzzle) was not verified until 2014, by Bousch.<ref>{{cite journal |first= T.|last=Bousch|title=La quatrieme tour de Hanoi|journal=Bull. Belg. Math. Soc. Simon Stevin|volume= 21|year=2014|pages=895–912 |doi=10.36045/bbms/1420071861|s2cid=14243013|url= https://pdfs.semanticscholar.org/fb87/0a772baf96a2e11901122a2b04c3dd25596d.pdf|archive-url= https://web.archive.org/web/20170921001150/https://pdfs.semanticscholar.org/fb87/0a772baf96a2e11901122a2b04c3dd25596d.pdf|url-status= dead|archive-date= 2017-09-21}}</ref>
Although the three-peg version has a simple recursive solution long been known, the optimal solution for the Tower of Hanoi problem with four pegs (called Reve's puzzle) was not verified until 2014, by Bousch.<ref>{{cite journal |first= T.|last=Bousch|title=La quatrieme tour de Hanoi|journal=Bull. Belg. Math. Soc. Simon Stevin|volume= 21|year=2014|issue=5|pages=895–912 |doi=10.36045/bbms/1420071861|s2cid=14243013|url= https://pdfs.semanticscholar.org/fb87/0a772baf96a2e11901122a2b04c3dd25596d.pdf|archive-url= https://web.archive.org/web/20170921001150/https://pdfs.semanticscholar.org/fb87/0a772baf96a2e11901122a2b04c3dd25596d.pdf|url-status= dead|archive-date= 2017-09-21}}</ref>


However, in case of four or more pegs, the Frame–Stewart algorithm is known without proof of optimality since 1941.<ref>{{cite journal |first1=B. M. |last1=Stewart |first2=J. S. |last2=Frame |title=Solution to advanced problem 3819 |journal=American Mathematical Monthly |volume=48 |issue=3 |pages=216–9 |doi=10.2307/2304268 |date=March 1941 |jstor=2304268}}</ref>
However, in case of four or more pegs, the Frame–Stewart algorithm is known without proof of optimality since 1941.<ref>{{cite journal |first1=B. M. |last1=Stewart |first2=J. S. |last2=Frame |title=Solution to advanced problem 3819 |journal=American Mathematical Monthly |volume=48 |issue=3 |pages=216–9 |doi=10.2307/2304268 |date=March 1941 |jstor=2304268}}</ref>
Line 277: Line 235:
For other variants of the four-peg Tower of Hanoi problem, see Paul Stockmeyer's survey paper.<ref>{{cite journal |first=Paul |last=Stockmeyer |title=Variations on the Four-Post Tower of Hanoi Puzzle |journal=Congressus Numerantium |volume=102 |year=1994 |pages=3–12 |url=http://www.cs.wm.edu/~pkstoc/boca.ps |format=Postscript}}</ref>
For other variants of the four-peg Tower of Hanoi problem, see Paul Stockmeyer's survey paper.<ref>{{cite journal |first=Paul |last=Stockmeyer |title=Variations on the Four-Post Tower of Hanoi Puzzle |journal=Congressus Numerantium |volume=102 |year=1994 |pages=3–12 |url=http://www.cs.wm.edu/~pkstoc/boca.ps |format=Postscript}}</ref>


The so-called Towers of Bucharest and Towers of Klagenfurt game configurations yield [[Ternary numeral system|ternary]] and pentary Gray codes.<ref name="Herter-Rote_2016"/>
The so-called Towers of Bucharest and Towers of Klagenfurt game configurations yield [[Ternary numeral system|ternary]] and [[pentary]] Gray codes.<ref name="Herter-Rote_2016"/>


==== Frame–Stewart algorithm ====
==== Frame–Stewart algorithm ====
Line 295: Line 253:
A curious generalization of the original goal of the puzzle is to start from a given configuration of the disks where all disks are not necessarily on the same peg and to arrive in a minimal number of moves at another given configuration. In general, it can be quite difficult to compute a shortest sequence of moves to solve this problem. A solution was proposed by Andreas Hinz and is based on the observation that in a shortest sequence of moves, the largest disk that needs to be moved (obviously one may ignore all of the largest disks that will occupy the same peg in both the initial and final configurations) will move either exactly once or exactly twice.
A curious generalization of the original goal of the puzzle is to start from a given configuration of the disks where all disks are not necessarily on the same peg and to arrive in a minimal number of moves at another given configuration. In general, it can be quite difficult to compute a shortest sequence of moves to solve this problem. A solution was proposed by Andreas Hinz and is based on the observation that in a shortest sequence of moves, the largest disk that needs to be moved (obviously one may ignore all of the largest disks that will occupy the same peg in both the initial and final configurations) will move either exactly once or exactly twice.


The mathematics related to this generalized problem becomes even more interesting when one considers the '''average''' number of moves in a shortest sequence of moves between two initial and final disk configurations that are chosen at random. Hinz and Chan Tat-Hung independently discovered<ref>{{cite journal |first=A. |last=Hinz |title=The Tower of Hanoi |journal=L'Enseignement Mathématique |volume=35 |year=1989 |pages=289–321 |doi=10.5169/seals-57378 }}</ref><ref>{{cite journal |first=T. |last=Chan |title=A statistical analysis of the towers of Hanoi problem |journal=Internat. J. Comput. Math. |volume=28 |issue=1–4 |year=1988 |pages=57–65 |doi=10.1080/00207168908803728}}</ref> (see also
The mathematics related to this generalized problem becomes even more interesting when one considers the ''average'' number of moves in a shortest sequence of moves between two initial and final disk configurations that are chosen at random. Hinz and Chan Tat-Hung independently discovered<ref>{{cite journal |first=A. |last=Hinz |title=The Tower of Hanoi |journal=L'Enseignement Mathématique |volume=35 |year=1989 |pages=289–321 |doi=10.5169/seals-57378 }}</ref><ref>{{cite journal |first=T. |last=Chan |title=A statistical analysis of the towers of Hanoi problem |journal=Internat. J. Comput. Math. |volume=28 |issue=1–4 |year=1988 |pages=57–65 |doi=10.1080/00207168908803728}}</ref> (see also
<ref>{{cite book |last=Stewart |first=Ian |title=Another Fine Math You've Got Me Into... |publisher=Courier Dover |year=2004 |isbn=978-0-7167-2342-4 }}</ref>{{rp|Chapter 1, p.&nbsp;14}})
<ref>{{cite book |last=Stewart |first=Ian |title=Another Fine Math You've Got Me Into... |publisher=Courier Dover |year=2004 |isbn=978-0-7167-2342-4 }}</ref>{{rp|Chapter 1, p.&nbsp;14}}) that the average number of moves in an n-disk Tower is given by the following exact formula:
that the average number of moves in an n-disk Tower is given by the following exact formula:


:<math> \frac{466}{885}\cdot 2^n - \frac{1}{3} - \frac{3}{5}\cdot \left(\frac{1}{3}\right)^n +
:<math> \frac{466}{885}\cdot 2^n - \frac{1}{3} - \frac{3}{5}\cdot \left(\frac{1}{3}\right)^n +
Line 303: Line 260:
\left(\frac{12}{59} - \frac{18}{1003}\sqrt{17}\right)\left(\frac{5-\sqrt{17}}{18}\right)^n.</math>
\left(\frac{12}{59} - \frac{18}{1003}\sqrt{17}\right)\left(\frac{5-\sqrt{17}}{18}\right)^n.</math>


For large enough ''n'', only the first and second terms do not converge to zero, so we get an [[asymptotic analysis|asymptotic expression]]: <math>466/885\cdot 2^n - 1/3 + o(1)</math>, as <math>n \to \infty</math>. Thus intuitively, we could interpret the fraction of <math>466/885\approx 52.6\%</math> as representing the ratio of the labor one has to perform when going from a randomly chosen configuration to another randomly chosen configuration, relative to the difficulty of having to cross the "most difficult" path of length <math>2^n-1</math> which involves moving all the disks from one peg to another. An alternative explanation for the appearance of the constant 466/885, as well as a new and somewhat improved algorithm for computing the shortest path, was given by Romik.<ref>{{cite journal |first=D. |last=Romik |title=Shortest paths in the Tower of Hanoi graph and finite automata |journal=[[SIAM Journal on Discrete Mathematics]] |volume=20 |issue=3 |year=2006 |pages=610–622 |doi=10.1137/050628660|arxiv=math/0310109 |s2cid=8342396 }}</ref>
For large enough ''n'', only the first and second terms do not converge to zero, so we get an [[asymptotic analysis|asymptotic expression]]: <math>466/885\cdot 2^n - 1/3 + o(1)</math>, as <math>n \to \infty</math>. Thus intuitively, we could interpret the fraction of <math>466/885\approx 52.6\%</math> as representing the ratio of the labor one has to perform when going from a randomly chosen configuration to another randomly chosen configuration, relative to the difficulty of having to cross the "most difficult" path of length <math>2^n - 1</math> which involves moving all the disks from one peg to another. An alternative explanation for the appearance of the constant 466/885, as well as a new and somewhat improved algorithm for computing the shortest path, was given by Romik.<ref>{{cite journal |first=D. |last=Romik |title=Shortest paths in the Tower of Hanoi graph and finite automata |journal=[[SIAM Journal on Discrete Mathematics]] |volume=20 |issue=3 |year=2006 |pages=610–622 |doi=10.1137/050628660|arxiv=math/0310109 |s2cid=8342396 }}</ref>


=== Magnetic Hanoi ===
=== Magnetic Hanoi ===
Line 322: Line 279:
===Tower of Hanoy===
===Tower of Hanoy===
<!--"Hanoy" here is the actual spelling used in the card game title, not a typo-->
<!--"Hanoy" here is the actual spelling used in the card game title, not a typo-->
A variation of the puzzle has been adapted as a solitaire game with nine playing cards under the name [[Tower of Hanoy]].<ref>{{Cite book|last=Arnold|first=Peter|url=https://books.google.com/books?id=M7C5-R0pGEQC&q=%22tower+of+hanoy%22&pg=PA70|title=Card Games for One|date=2003-05-28|publisher=Sterling Publishing Company|isbn=978-0-600-60727-4|language=en}}</ref><ref>{{Cite book|last=Hedges|first=Sid G.|url=https://books.google.com/books?id=Jd1PDwAAQBAJ&q=%22tower+of+hanoy%22&pg=PT141|title=Everybody's Book of Hobbies|date=2018-03-06|publisher=Read Books Ltd|isbn=978-1-5287-8344-6|language=en}}</ref> It is not known whether the altered spelling of the original name is deliberate or accidental.<ref>{{Cite web|title=Tower Of Hanoy Patience (AKA Tower Of Hanoi Patience)|url=http://bbcmicro.co.uk//game.php?id=3366&h=h|access-date=2020-10-17|website=bbcmicro.co.uk|language=en}}</ref>
A variation of the puzzle has been adapted as a [[Solitaire (game)|solitaire game]] with nine playing cards under the name [[Tower of Hanoy]].<ref>{{Cite book|last=Arnold|first=Peter|url=https://books.google.com/books?id=M7C5-R0pGEQC&q=%22tower+of+hanoy%22&pg=PA70|title=Card Games for One|date=2003-05-28|publisher=Sterling Publishing Company|isbn=978-0-600-60727-4|language=en}}</ref><ref>{{Cite book|last=Hedges|first=Sid G.|url=https://books.google.com/books?id=Jd1PDwAAQBAJ&q=%22tower+of+hanoy%22&pg=PT141|title=Everybody's Book of Hobbies|date=2018-03-06|publisher=Read Books Ltd|isbn=978-1-5287-8344-6|language=en}}</ref> It is not known whether the altered spelling of the original name is deliberate or accidental.<ref>{{Cite web|title=Tower Of Hanoy Patience (AKA Tower Of Hanoi Patience)|url=http://bbcmicro.co.uk//game.php?id=3366&h=h|access-date=2020-10-17|website=bbcmicro.co.uk|language=en}}</ref>


== Applications ==
== Applications ==
[[File:Palladium nanosheet on silicon wafer.jpg|thumb|3D AFM topographic image of multilayered palladium nanosheet on silicon wafer, with Tower of Hanoi-like structure.<ref name="Nano">{{cite journal|last1=Yin|first1=Xi|last2=Liu|first2=Xinhong|last3=Pan|first3=Yung-Tin|last4=Walsh|first4=Kathleen A.|last5=Yang|first5=Hong|title=Hanoi Tower-like Multilayered Ultrathin Palladium Nanosheets|journal=Nano Letters|date=November 4, 2014|doi=10.1021/nl503879a|pmid=25369350|volume=14|issue=12|pages=7188–94|bibcode=2014NanoL..14.7188Y}}</ref>]]
[[File:Palladium nanosheet on silicon wafer.jpg|thumb|3D AFM topographic image of multilayered palladium nanosheet on silicon wafer, with Tower of Hanoi-like structure.<ref name="Nano">{{cite journal|last1=Yin|first1=Xi|last2=Liu|first2=Xinhong|last3=Pan|first3=Yung-Tin|last4=Walsh|first4=Kathleen A.|last5=Yang|first5=Hong|title=Hanoi Tower-like Multilayered Ultrathin Palladium Nanosheets|journal=Nano Letters|date=November 4, 2014|doi=10.1021/nl503879a|pmid=25369350|volume=14|issue=12|pages=7188–94|bibcode=2014NanoL..14.7188Y}}</ref>]]
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 Test|Tower of London]] for neuropsychological diagnosis and treatment of executive functions.
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 Test|Tower of London]] for neuropsychological diagnosis and treatment of disorders of [[executive function]].<ref>{{Cite journal |date=1982-06-25 |title=Specific impairments of planning |url=https://royalsocietypublishing.org/doi/10.1098/rstb.1982.0082 |journal=Philosophical Transactions of the Royal Society of London. B, Biological Sciences |language=en |volume=298 |issue=1089 |pages=199–209 |doi=10.1098/rstb.1982.0082 |pmid=6125971 |issn=0080-4622 |last1=Shallice |first1=T. |bibcode=1982RSPTB.298..199S }}</ref>


Zhang and Norman<ref>{{cite journal|doi=10.1016/0364-0213(94)90021-3|url=http://wexler.free.fr/library/files/zhang%20%281994%29%20representations%20in%20distributed%20cognitive%20tasks.pdf|title=Representations in distributed cognitive tasks|journal=Cognitive Science|volume=18|pages=87–122|year=1994|last1=Zhang|first1=J}}</ref> used several isomorphic (equivalent) representations of the game to study the impact of representational effect in task design. They demonstrated an impact on user performance by changing the way that the rules of the game are represented, using variations in the physical design of the game components. This knowledge has impacted on the development of the TURF framework<ref>{{Cite journal|doi=10.1016/j.jbi.2011.08.005|pmid=21867774|title=TURF: Toward a unified framework of EHR usability|journal=Journal of Biomedical Informatics|volume=44|issue=6|pages=1056–67|year=2011|last1=Zhang|first1=Jiajie|last2=Walji|first2=Muhammad F.|doi-access=free}}</ref> for the representation of [[human–computer interaction]].
Zhang and Norman<ref>{{cite journal|doi=10.1016/0364-0213(94)90021-3|url=http://wexler.free.fr/library/files/zhang%20%281994%29%20representations%20in%20distributed%20cognitive%20tasks.pdf|title=Representations in distributed cognitive tasks|journal=Cognitive Science|volume=18|pages=87–122|year=1994|last=Zhang|first=J}}</ref> used several isomorphic (equivalent) representations of the game to study the impact of [[representational effect]] in task design. They demonstrated an impact on user performance by changing the way that the rules of the game are represented, using variations in the physical design of the game components. This knowledge has impacted on the development of the TURF framework<ref>{{Cite journal|doi=10.1016/j.jbi.2011.08.005|pmid=21867774|title=TURF: Toward a unified framework of EHR usability|journal=Journal of Biomedical Informatics|volume=44|issue=6|pages=1056–67|year=2011|last1=Zhang|first1=Jiajie|last2=Walji|first2=Muhammad F.|doi-access=free}}</ref> for the representation of [[human–computer interaction]].


The Tower of Hanoi is also used as a [[backup rotation scheme]] when performing computer data [[backups]] where multiple tapes/media are involved.
The Tower of Hanoi is also used as a [[backup rotation scheme]] when performing computer data backups where multiple tapes/media are involved.<ref>{{Cite report |url=https://doi.org/10.21236/ada218927 |title=Tower-Noticing Triggers Strategy-Change in the Tower of Hanoi: A Soar Model |last=Ruiz |first=Dirk |last2=Newell |first2=Allen |date=1989-06-01 |publisher=Defense Technical Information Center |location=Fort Belvoir, VA}}</ref>


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]].
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]].{{citation needed |date=September 2023}}


The Tower of Hanoi is also used as a test by neuropsychologists trying to evaluate [[frontal lobe]] deficits.<ref>{{Cite journal | url=https://ajp.psychiatryonline.org/doi/pdf/10.1176/ajp.156.5.777 | doi=10.1176/ajp.156.5.777| pmid=10327915| year=1999| last1=Beers| first1=S. R.| title=Neuropsychological study of frontal lobe function in psychotropic-naive children with obsessive-compulsive disorder| journal=The American Journal of Psychiatry| volume=156| issue=5| pages=777–9| last2=Rosenberg| first2=D. R.| last3=Dick| first3=E. L.| last4=Williams| first4=T.| last5=O'Hearn| first5=K. M.| last6=Birmaher| first6=B.| last7=Ryan| first7=C. M.| doi-broken-date=31 May 2021}}</ref>
The Tower of Hanoi is also used as a test by neuropsychologists trying to evaluate [[frontal lobe]] deficits.<ref>{{Cite journal | url=https://ajp.psychiatryonline.org/doi/pdf/10.1176/ajp.156.5.777 | doi=10.1176/ajp.156.5.777| pmid=10327915| year=1999| last1=Beers| first1=S. R.| title=Neuropsychological study of frontal lobe function in psychotropic-naive children with obsessive-compulsive disorder| journal=The American Journal of Psychiatry| volume=156| issue=5| pages=777–9| last2=Rosenberg| first2=D. R.| last3=Dick| first3=E. L.| last4=Williams| first4=T.| last5=O'Hearn| first5=K. M.| last6=Birmaher| first6=B.| last7=Ryan| first7=C. M.| s2cid=21359382}}</ref>


In 2010, researchers published the results of an experiment that found that the ant species ''[[Linepithema humile]]'' were successfully able to solve the 3-disk version of the Tower of Hanoi problem through non-linear dynamics and pheromone signals.<ref>{{cite journal |last1=Reid |first1=C.R. |last2=Sumpter |first2=D.J. |last3=Beekman |first3=M. |title=Optimisation in a natural system: Argentine ants solve the Towers of Hanoi |journal=J. Exp. Biol. |volume=214 |issue=Pt 1 |pages=50–8 |date=January 2011 |pmid=21147968 |doi=10.1242/jeb.048173 |citeseerx=10.1.1.231.9201 |s2cid=18819977 }}</ref>
In 2010, researchers published the results of an experiment that found that the ant species ''[[Linepithema humile]]'' were successfully able to solve the 3-disk version of the Tower of Hanoi problem through non-linear dynamics and pheromone signals.<ref>{{cite journal |last1=Reid |first1=C.R. |last2=Sumpter |first2=D.J. |last3=Beekman |first3=M. |title=Optimisation in a natural system: Argentine ants solve the Towers of Hanoi |journal=J. Exp. Biol. |volume=214 |issue=Pt 1 |pages=50–8 |date=January 2011 |pmid=21147968 |doi=10.1242/jeb.048173 |citeseerx=10.1.1.231.9201 |s2cid=18819977 }}</ref>


In 2014, scientists synthesized multilayered palladium nanosheets with a Tower of Hanoi like structure.<ref name="Nano" />
In 2014, scientists synthesized multilayered [[palladium]] nanosheets with a Tower of Hanoi-like structure.<ref name="Nano"/>


== In popular culture ==
== In popular culture ==
In the science fiction story "Now Inhale", by [[Eric Frank Russell]], a human is held prisoner on a planet where the local custom is to make the prisoner play a game until it is won or lost before his execution. The protagonist knows that a rescue ship might take a year or more to arrive, so he chooses to play Towers of Hanoi with 64 disks. This story makes reference to the legend about the Buddhist monks playing the game until the end of the world.<ref>{{cite magazine |journal=Astounding Science Fiction |date=April 1959 |first=Eric Frank |last=Russell |title=Now Inhale |volume = 63 |issue = 2 |department=Novelettes |pages=31–77 |url=https://archive.org/details/Astounding_v63n02_1959-04_EXciter-LennyS/page/n30/mode/1up}}
In the science fiction story "Now Inhale", by [[Eric Frank Russell]], a human is held prisoner on a planet where the local custom is to make the prisoner play a game until it is won or lost before his execution. The protagonist knows that a rescue ship might take a year or more to arrive, so he chooses to play Towers of Hanoi with 64 disks. This story makes reference to the legend about the Buddhist monks playing the game until the end of the world.<ref>{{cite magazine |journal=Astounding Science Fiction |date=April 1959 |first=Eric Frank |last=Russell |title=Now Inhale |volume = 63 |issue = 2 |department=Novelettes |pages=31–77 |url=https://archive.org/details/Astounding_v63n02_1959-04_EXciter-LennyS/page/n30/mode/1up}}
* Reprinted: {{cite book| editor-last=Katze |editor-first=Rick |title=Major Ingredients: The Selected Short Stories of Eric Frank Russell |date=2000 |pages=399–417 |chapter=Now Inhale |last=Russell |first=Eric Frank |location=Framingham, Mass. |publisher=NESFA Press |isbn=978-1-886778-10-8 |ref=none}}</ref><ref name="Self-Similar Groups">{{cite book |last1=Bonanome |first1=Marianna C. |last2=Dean |first2=Margaret H. |last3=Dean |first3=Judith Putnam |title=A Sampling of Remarkable Groups: Thompson's, Self-similar, Lamplighter, and Baumslag-Solitar |date=2018 |publisher=Springer |location=Cham, Switzerland |doi=10.1007/978-3-030-01978-5_3 |page=96 |chapter=Self-Similar Groups|series=Compact Textbooks in Mathematics |isbn=978-3-030-01976-1 }}</ref><ref>{{cite journal |last1=Birtwistle |first1=Graham |title=The coroutines of Hanoi |journal=ACM SIGPLAN Notices |date=January 1985 |volume=20 |issue=1 |pages=9–10 |doi=10.1145/988284.988286 |s2cid=7310661 }}</ref>
* Reprinted: {{cite book| editor-last=Katze |editor-first=Rick |title=Major Ingredients: The Selected Short Stories of Eric Frank Russell |date=2000 |pages=399–417 |chapter=Now Inhale |last=Russell |first=Eric Frank |location=Framingham, Mass. |publisher=NESFA Press |isbn=978-1-886778-10-8 |ref=none}}</ref><ref name="Self-Similar Groups">{{cite book |last1=Bonanome |first1=Marianna C. |last2=Dean |first2=Margaret H. |last3=Dean |first3=Judith Putnam |title=A Sampling of Remarkable Groups: Thompson's, Self-similar, Lamplighter, and Baumslag-Solitar |date=2018 |publisher=Springer |location=Cham, Switzerland |doi=10.1007/978-3-030-01978-5_3 |page=96 |chapter=Self-Similar Groups|series=Compact Textbooks in Mathematics |isbn=978-3-030-01976-1 }}</ref><ref>{{cite journal |last=Birtwistle |first=Graham |title=The coroutines of Hanoi |journal=ACM SIGPLAN Notices |date=January 1985 |volume=20 |issue=1 |pages=9–10 |doi=10.1145/988284.988286 |s2cid=7310661 }}</ref>


In the 1966 ''[[Doctor Who]]'' story ''[[The Celestial Toymaker]]'', the [[eponym]]ous villain forces [[The Doctor (Doctor Who)|the Doctor]] to play a ten-piece 1,023-move Tower of Hanoi game entitled [[List of Doctor Who items#T|The Trilogic Game]] with the pieces forming a pyramid shape when stacked.<ref name="Self-Similar Groups"/><ref>{{cite web |title=The Fourth Dimension: The Celestial Toymaker |url=https://www.bbc.co.uk/programmes/articles/3DHlYgfSdY2RlXkS2KwjtKK/the-fourth-dimension |website=Doctor Who |publisher=BBC One |access-date=April 2, 2021}}</ref>
In the 1966 ''[[Doctor Who]]'' story ''[[The Celestial Toymaker]]'', the [[eponym]]ous villain forces [[the Doctor]] to play a ten-piece, [[1,023]]-move Tower of Hanoi game entitled The Trilogic Game with the pieces forming a pyramid shape when stacked.<ref name="Self-Similar Groups"/><ref>{{cite web |title=The Fourth Dimension: The Celestial Toymaker |url=https://www.bbc.co.uk/programmes/articles/3DHlYgfSdY2RlXkS2KwjtKK/the-fourth-dimension |website=Doctor Who |publisher=BBC One |access-date=April 2, 2021}}</ref>


In 2007, the concept of the Towers Of Hanoi problem was used in ''[[Professor Layton and the Diabolical Box]]'' in puzzles 6, 83, and 84, but the disks had been changed to pancakes. The puzzle was based around a dilemma where the chef of a restaurant had to move a pile of pancakes from one plate to the other with the basic principles of the original puzzle (i.e. three plates that the pancakes could be moved onto, not being able to put a larger pancake onto a smaller one, etc.)
In 2007, the concept of the Towers Of Hanoi problem was used in ''[[Professor Layton and the Diabolical Box]]'' in puzzles 6, 83, and 84, but the disks had been changed to pancakes. The puzzle was based around a dilemma where the chef of a restaurant had to move a pile of pancakes from one plate to the other with the basic principles of the original puzzle (i.e. three plates that the pancakes could be moved onto, not being able to put a larger pancake onto a smaller one, etc.)


In the film ''[[Rise of the Planet of the Apes]]'' (2011), this puzzle, called in the film the "Lucas Tower", is used as a test to study the intelligence of apes.<ref name="Self-Similar Groups"/><ref>{{cite web |last1=Weisstein |first1=Eric W. |title=Tower of Hanoi |url=https://mathworld.wolfram.com/TowerofHanoi.html |website=MathWorld |publisher=Wolfram |access-date=April 2, 2021 |language=en}}</ref>
In the 2011 film ''[[Rise of the Planet of the Apes]]'', this puzzle, called in the film the "Lucas Tower", is used as a test to study the [[intelligence of apes]].<ref name="Self-Similar Groups"/>


The puzzle is featured regularly in [[adventure game|adventure]] and [[computer puzzle game|puzzle]] games. Since it is easy to implement, and easily recognised, it is well-suited to use as a puzzle in a larger graphical game (e.g. ''[[Star Wars: Knights of the Old Republic (video game)|Star Wars: Knights of the Old Republic]]'' and ''[[Mass Effect (video game)|Mass Effect]]'').<ref>{{cite web |url=http://www.giantbomb.com/tower-of-hanoi/92-5744/ |title=Tower of Hanoi (video game concept) |publisher=Giantbomb.com |access-date=2010-12-05}}</ref> Some implementations use straight disks, but others disguise the puzzle in some other form. There is an arcade version by [[Sega]].<ref>{{cite web|url=http://www.segaarcade.com/towerofhanoi |title=Tower of Hanoi / Andamiro |publisher=Sega Amusements |access-date=2012-02-26 |url-status=dead |archive-url=https://web.archive.org/web/20120301060428/http://www.segaarcade.com/towerofhanoi |archive-date=2012-03-01 }}</ref>
The puzzle is featured regularly in [[adventure game|adventure]] and [[computer puzzle game|puzzle]] games. Since it is easy to implement, and easily recognised, it is well suited to use as a puzzle in a larger graphical game (e.g. ''[[Star Wars: Knights of the Old Republic (video game)|Star Wars: Knights of the Old Republic]]'' and ''[[Mass Effect (video game)|Mass Effect]]'').<ref>{{cite web |url=http://www.giantbomb.com/tower-of-hanoi/92-5744/ |title=Tower of Hanoi (video game concept) |publisher=Giantbomb.com |access-date=2010-12-05}}</ref> Some implementations use straight disks, but others disguise the puzzle in some other form. There is an arcade version by [[Sega]].<ref>{{cite web|url=http://www.segaarcade.com/towerofhanoi |title=Tower of Hanoi / Andamiro |publisher=Sega Amusements |access-date=2012-02-26 |url-status=dead |archive-url=https://web.archive.org/web/20120301060428/http://www.segaarcade.com/towerofhanoi |archive-date=2012-03-01 }}</ref>


A 15-disk version of the puzzle appears in the game ''[[Sunless Sea]]'' as a lock to a tomb. The player has the option to click through each move of the puzzle in order to solve it, but the game notes that it will take 32767 moves to complete. If an especially dedicated player does click through to the end of the puzzle, it is revealed that completing the puzzle does not unlock the door.
A 15-disk version of the puzzle appears in the game ''[[Sunless Sea]]'' as a lock to a tomb. The player has the option to click through each move of the puzzle in order to solve it, but the game notes that it will take [[32,767]] moves to complete. If an especially dedicated player does click through to the end of the puzzle, it is revealed that completing the puzzle does not unlock the door.

In ''[[Yu-Gi-Oh! VRAINS]]'', a hacking group called "Knight of Hanoi" create a structure named "Tower of Hanoi" within the eponymous VRAINS virtual reality network.


This was first used as a challenge in ''Survivor'' Thailand in 2002 but rather than rings, the pieces were made to resemble a temple. Sook Jai threw the challenge to get rid of Jed even though Shii-Ann knew full well how to complete the puzzle.
This was first used as a challenge in ''Survivor'' Thailand in 2002 but rather than rings, the pieces were made to resemble a temple. Sook Jai threw the challenge to get rid of Jed even though Shii-Ann knew full well how to complete the puzzle.
The problem is featured as part of a reward challenge in a [[Survivor: South Pacific#Episode 1: "I Need Redemption"|2011 episode of the American version of the ''Survivor'' TV series]]. Both players ([[Ozzy Lusth]] and [[Benjamin Wade (Survivor contestant)|Benjamin "Coach" Wade]]) struggled to understand how to solve the puzzle and are aided by their fellow tribe members.
The problem is featured as part of a reward challenge in a [[Survivor: South Pacific#Episode 1: "I Need Redemption"|2011 episode of the American version of the ''Survivor'' TV series]]. Both players ([[Ozzy Lusth]] and [[Coach (Survivor contestant)|Benjamin "Coach" Wade]]) struggled to understand how to solve the puzzle and are aided by their fellow tribe members.

In ''[[Genshin Impact]]'', this puzzle is shown in Faruzan's hangout quest, "Early Learning Mechanism", where she mentions seeing it as a mechanism and uses it to make a toy prototype for children. She calls it [[pagoda]] stacks.


== See also ==
== See also ==
Line 365: Line 322:
* [[Baguenaudier]]
* [[Baguenaudier]]
* [[Recursion (computer science)]]
* [[Recursion (computer science)]]
* "[[The Nine Billion Names of God]]", 1953 Arthur C. Clark short story with a similar premise to the game's framing story
{{-}}
{{Clear}}


== Notes ==
== Notes ==
{{reflist|refs=
{{reflist|refs=
<ref name="Herter-Rote_2016">{{cite paper |title=Loopless Gray Code Enumeration and the Tower of Bucharest |author-first1=Felix |author-last1=Herter |author-first2=Günter |author-last2=Rote |publication-place=Berlin, Germany |orig-date=2018-08-09, 2017-12, 2017-08-09, 2016-04-22 |date=2018-11-14 |journal=[[Theoretical Computer Science (journal)|Theoretical Computer Science]] |issn=0304-3975 |volume=748 |arxiv=1604.06707<!-- 24 pages --> |s2cid=4014870 |doi=10.1016/j.tcs.2017.11.017 |pages=40–54 |url=https://page.mi.fu-berlin.de/rote/Papers/pdf/Loopless+Gray+code+enumeration+and+the+Tower+of+Bucharest.pdf<!-- 18 pages --> |access-date=2020-12-16 |url-status=live |archive-url=https://web.archive.org/web/20201216150701/https://page.mi.fu-berlin.de/rote/Papers/pdf/Loopless+Gray+code+enumeration+and+the+Tower+of+Bucharest.pdf |archive-date=2020-12-16}} [https://web.archive.org/web/20201216230211/https://arxiv.org/pdf/1604.06707.pdf] (15/18/19/24 pages)</ref>
<ref name="Herter-Rote_2016">{{cite journal |title=Loopless Gray Code Enumeration and the Tower of Bucharest |first1=Felix |last1=Herter |first2=Günter |last2=Rote |publication-place=Berlin, Germany |orig-date=2018-08-09, 2017-12, 2017-08-09, 2016-04-22 |date=2018-11-14 |journal=[[Theoretical Computer Science (journal)|Theoretical Computer Science]] |issn=0304-3975 |volume=748 |arxiv=1604.06707<!-- 24 pages --> |s2cid=4014870 |doi=10.1016/j.tcs.2017.11.017 |pages=40–54 |url=https://page.mi.fu-berlin.de/rote/Papers/pdf/Loopless+Gray+code+enumeration+and+the+Tower+of+Bucharest.pdf<!-- 18 pages --> |access-date=2020-12-16 |url-status=live |archive-url=https://web.archive.org/web/20201216150701/https://page.mi.fu-berlin.de/rote/Papers/pdf/Loopless+Gray+code+enumeration+and+the+Tower+of+Bucharest.pdf |archive-date=2020-12-16}} [https://web.archive.org/web/20201216230211/https://arxiv.org/pdf/1604.06707.pdf] (15/18/19/24 pages)</ref>
}}
}}


Line 376: Line 334:
* {{mathworld|title=Tower of Hanoi|urlname=TowerofHanoi}}
* {{mathworld|title=Tower of Hanoi|urlname=TowerofHanoi}}


[[Category:1883 introductions]]
[[Category:1889 documents]]
[[Category:19th-century inventions]]
[[Category:French inventions]]
[[Category:Mechanical puzzles]]
[[Category:Mechanical puzzles]]
[[Category:Mathematical puzzles]]
[[Category:Mathematical puzzles]]
[[Category:Articles with example C code]]
[[Category:Articles with example Python (programming language) code]]
[[Category:Articles with example Python (programming language) code]]
[[Category:Divide-and-conquer algorithms]]

Latest revision as of 08:04, 17 December 2024

A model set of the Tower of Hanoi (with 8 disks)
An animated solution of the Tower of Hanoi puzzle for T(4, 3)
Tower of Hanoi interactive display at Mexico City's Universum Museum

The Tower of Hanoi (also called The problem of Benares Temple[1] or Tower of Brahma or Lucas' Tower[2] and sometimes pluralized as Towers, or simply pyramid puzzle[3]) is a mathematical game or puzzle consisting of three rods and a number of disks of various diameters, which can slide onto any rod. The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top, thus approximating a conical shape. The objective of the puzzle is to move the entire stack to one of the other rods, obeying the following rules:[4]

  1. Only one disk may be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
  3. No disk may be placed on top of a disk that is smaller than it.

With three disks, the puzzle can be solved in seven moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.

Origins

[edit]

The puzzle was invented by the French mathematician Édouard Lucas, first presented in 1883 as a game discovered by "N. Claus (de Siam)" (an anagram of "Lucas d'Amiens"),[5][6][7] and later published as a booklet in 1889[8] and in a posthumously-published volume of Lucas' Récréations mathématiques.[9] Accompanying the game was an instruction booklet, describing the game's purported origins in Tonkin, and claiming that according to legend Brahmins at a temple in Benares have been carrying out the movement of the "Sacred Tower of Brahma", consisting of sixty-four golden disks, according to the same rules as in the game, and that the completion of the tower would lead to the end of the world.[10] Numerous variations on this legend regarding the ancient and mystical nature of the puzzle popped up almost immediately.[5]

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 to finish,[11] which is about 42 times the estimated current age of the universe.

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 in various locales including Hanoi, 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.

Solution

[edit]

The puzzle can be played with any number of disks, although many toy versions have around 7 to 9 of them. The minimal number of moves required to solve a Tower of Hanoi puzzle with n disks is 2n − 1.[12]

Iterative solution

[edit]
Animation of an iterative algorithm-solving 6-disk problem

A simple solution for the toy puzzle is to alternate moves between the smallest piece and a non-smallest piece. When moving the smallest piece, always move it to the next position 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 position 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 in the fewest moves.[13]

Simpler statement of iterative solution

[edit]

The iterative solution is equivalent to repeated execution of the following sequence of steps until the goal has been achieved:

  • Move one disk from peg A to peg B or vice versa, whichever move is legal.
  • Move one disk from peg A to peg C or vice versa, whichever move is legal.
  • Move one disk from peg B to peg C or vice versa, whichever move is legal.

Following this approach, the stack will end up on peg B if the number of disks is odd and peg C if it is even.

Recursive solution

[edit]
Illustration of a recursive solution for the Towers of Hanoi puzzle with 4 disks. In the SVG file, click a grey button to expand or collapse it

The key to solving a problem recursively is to recognize that it can be broken down into a collection of smaller sub-problems, to each of which that same general solving procedure that we are seeking applies[citation needed], and the total solution is then found in some simple way from those sub-problems' solutions. Each of these created sub-problems being "smaller" guarantees that the base case(s) will eventually be reached. For the Towers of Hanoi:

  • label the pegs A, B, C,
  • let n be the total number of disks, and
  • number the disks from 1 (smallest, topmost) to n (largest, bottom-most).

Assuming all n disks are distributed in valid arrangements among the pegs; assuming there are m top disks on a source peg, and all the rest of the disks are larger than m, so they can be safely ignored; to move m disks from a source peg to a target peg using a spare peg, without violating the rules:

  1. Move m − 1 disks from the source to the spare peg, by the same general solving procedure. Rules are not violated, by assumption. This leaves the disk m as a top disk on the source peg.
  2. Move the disk m from the source to the target peg, which is guaranteed to be a valid move, by the assumptions — a simple step.
  3. Move the m − 1 disk that we have just placed on the spare, from the spare to the target peg by the same general solving procedure, so they are placed on top of the disk m without violating the rules.
  4. The base case is to move 0 disks (in steps 1 and 3), that is, do nothing—which does not violate the rules.

The full Tower of Hanoi solution then moves n disks from the source peg A to the target peg C, using B as the spare peg.

This approach can be given a rigorous mathematical proof with mathematical induction and is often used as an example of recursion when teaching programming.

Logical analysis of the recursive solution

[edit]

As in many mathematical puzzles, finding a solution is made easier by solving a slightly more general problem: how to move a tower of h (height) disks from a starting peg f = A (from) onto a destination peg t = C (to), B being the remaining third peg and assuming tf. First, observe that the problem is symmetric for permutations of the names of the pegs (symmetric group S3). If a solution is known moving from peg A to peg C, then, by renaming the pegs, the same solution can be used for every other choice of starting and destination peg. If there is only one disk (or even none at all), the problem is trivial. If h = 1, then move the disk from peg A to peg C. If h > 1, then somewhere along the sequence of moves, the largest disk must be moved from peg A to another peg, preferably to peg C. The only situation that allows this move is when all smaller h − 1 disks are on peg B. Hence, first all h − 1 smaller disks must go from A to B. Then move the largest disk and finally move the h − 1 smaller disks from peg B to peg C. The presence of the largest disk does not impede any move of the h − 1 smaller disks and can be temporarily ignored. Now the problem is reduced to moving h − 1 disks from one peg to another one, first from A to B and subsequently from B to C, but the same method can be used both times by renaming the pegs. The same strategy can be used to reduce the h − 1 problem to h − 2, h − 3, and so on until only one disk is left. This is called recursion. This algorithm can be schematized as follows.

Identify the disks in order of increasing size by the natural numbers from 0 up to but not including h. Hence disk 0 is the smallest one, and disk h − 1 the largest one.

The following is a procedure for moving a tower of h disks from a peg A onto a peg C, with B being the remaining third peg:

  1. If h > 1, then first use this procedure to move the h − 1 smaller disks from peg A to peg B.
  2. Now the largest disk, i.e. disk h can be moved from peg A to peg C.
  3. If h > 1, then again use this procedure to move the h − 1 smaller disks from peg B to peg C.

By mathematical induction, it is easily proven that the above procedure requires the minimum number of moves possible and that the produced solution is the only one with this minimal number of moves. Using recurrence relations, the exact number of moves that this solution requires can be calculated by: . This result is obtained by noting that steps 1 and 3 take moves, and step 2 takes one move, giving .

Non-recursive solution

[edit]

The list of moves for a tower being carried from one peg onto another one, as produced by the recursive algorithm, has many regularities. When counting the moves starting from 1, the ordinal of the disk to be moved during move m is the number of times m can be divided by 2. Hence every odd move involves the smallest disk. It can also be observed that the smallest disk traverses the pegs f, t, r, f, t, r, etc. for odd height of the tower and traverses the pegs f, r, t, f, r, t, etc. for even height of the tower. This provides the following algorithm, which is easier, carried out by hand, than the recursive algorithm.

In alternate moves:

  • Move the smallest disk to the peg it has not recently come from.
  • Move another disk legally (there will be only one possibility).

For the very first move, the smallest disk goes to peg t if h is odd and to peg r if h is even.

Also observe that:

  • Disks whose ordinals have even parity move in the same sense as the smallest disk.
  • Disks whose ordinals have odd parity move in opposite sense.
  • If h is even, the remaining third peg during successive moves is t, r, f, t, r, f, etc.
  • If h is odd, the remaining third peg during successive moves is r, t, f, r, t, f, etc.

With this knowledge, a set of disks in the middle of an optimal solution can be recovered with no more state information than the positions of each disk:

  • Call the moves detailed above a disk's "natural" move.
  • Examine the smallest top disk that is not disk 0, and note what its only (legal) move would be: if there is no such disk, then we are either at the first or last move.
  • If that move is the disk's "natural" move, then the disk has not been moved since the last disk 0 move, and that move should be taken.
  • If that move is not the disk's "natural" move, then move disk 0.

Binary solution

[edit]

Disk positions may be determined more directly from the binary (base-2) representation of the move number (the initial state being move #0, with all digits 0, and the final state being with all digits 1), using the following rules:

  • There is one binary digit (bit) for each disk.
  • The most significant (leftmost) bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it is on the final peg (right peg if number of disks is odd and middle peg otherwise).
  • The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk.
  • A bit with the same value as the previous one means that the corresponding disk is stacked on top of the previous disk on the same peg.
    (That is to say: a straight sequence of 1s or 0s means that the corresponding disks are all on the same peg.)
  • A bit with a different value to the previous one means that the corresponding disk is one position to the left or right of the previous one. Whether it is left or right is determined by this rule:
    • Assume that the initial peg is on the left.
    • Also assume "wrapping"—so the right peg counts as one peg "left" of the left peg, and vice versa.
    • Let n be the number of greater disks that are located on the same peg as their first greater disk and add 1 if the largest disk is on the left peg. If n is even, the disk is located one peg to the right, if n is odd, the disk located one peg to the left (in case of an even number of disks and vice versa otherwise).

For example, in an 8-disk Hanoi:

  • Move 0 = 00000000.
    • The largest disk is 0, so it is on the left (initial) peg.
    • All other disks are 0 as well, so they are stacked on top of it. Hence all disks are on the initial peg.
  • Move 28 − 1 = 11111111.
    • The largest disk is 1, so it is on the middle (final) peg.
    • All other disks are 1 as well, so they are stacked on top of it. Hence all disks are on the final peg and the puzzle is complete.
  • Move 21610 = 11011000.
    • The largest disk is 1, so it is on the middle (final) peg.
    • Disk two is also 1, so it is stacked on top of it, on the middle peg.
    • Disk three is 0, so it is on another peg. Since n is odd (n = 1), it is one peg to the left, i.e. on the left peg.
    • Disk four is 1, so it is on another peg. Since n is odd (n = 1), it is one peg to the left, i.e. on the right peg.
    • Disk five is also 1, so it is stacked on top of it, on the right peg.
    • Disk six is 0, so it is on another peg. Since n is even (n = 2), the disk is one peg to the right, i.e. on the left peg.
    • Disks seven and eight are also 0, so they are stacked on top of it, on the left peg.

The source and destination pegs for the mth move can also be found elegantly from the binary representation of m using bitwise operations. To use the syntax of the C programming language, move m is from peg (m & m - 1) % 3 to peg ((m | m - 1) + 1) % 3, where the disks begin on peg 0 and finish on peg 1 or 2 according as whether the number of disks is even or odd. Another formulation is from peg (m - (m & -m)) % 3 to peg (m + (m & -m)) % 3.

Furthermore, the disk to be moved is determined by the number of times the move count (m) can be divided by 2 (i.e. the number of zero bits at the right), counting the first move as 1 and identifying the disks by the numbers 0, 1, 2, etc. in order of increasing size. This permits a very fast non-recursive computer implementation to find the positions of the disks after m moves without reference to any previous move or distribution of disks.

The operation, which counts the number of consecutive zeros at the end of a binary number, gives a simple solution to the problem: the disks are numbered from zero, and at move m, disk number count trailing zeros is moved the minimal possible distance to the right (circling back around to the left as needed).[14]

Gray-code solution

[edit]

The binary numeral system of Gray codes gives an alternative way of solving the puzzle. In the Gray system, numbers are expressed in a binary combination of 0s and 1s, but rather than being a standard positional numeral system, the Gray code operates on the premise that each value differs from its predecessor by only one bit changed.

If one counts in Gray code of a bit size equal to the number of disks in a particular Tower of Hanoi, begins at zero and counts up, then the bit changed each move corresponds to the disk to move, where the least-significant bit is the smallest disk, and the most-significant bit is the largest.

Counting moves from 1 and identifying the disks by numbers starting from 0 in order of increasing size, the ordinal of the disk to be moved during move m is the number of times m can be divided by 2.

This technique identifies which disk to move, but not where to move it to. For the smallest disk, there are always two possibilities. For the other disks there is always one possibility, except when all disks are on the same peg, but in that case either it is the smallest disk that must be moved or the objective has already been achieved. Luckily, there is a rule that does say where to move the smallest disk to. Let f be the starting peg, t the destination peg, and r the remaining third peg. If the number of disks is odd, the smallest disk cycles along the pegs in the order ftrftr, etc. If the number of disks is even, this must be reversed: frtfrt, etc.[15]

The position of the bit change in the Gray code solution gives the size of the disk moved at each step: 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, ... (sequence A001511 in the OEIS),[16] a sequence also known as the ruler function, or one more than the power of 2 within the move number. In the Wolfram Language, IntegerExponent[Range[2^8 - 1], 2] + 1 gives moves for the 8-disk puzzle.

Graphical representation

[edit]

The game can be represented by an undirected graph, the nodes representing distributions of disks and the edges representing moves. For one disk, the graph is a triangle:

The graph for two disks is three triangles connected to form the corners of a larger triangle.

A second letter is added to represent the larger disk. Clearly, it cannot initially be moved.

The topmost small triangle now represents the one-move possibilities with two disks:

The nodes at the vertices of the outermost triangle represent distributions with all disks on the same peg.

For h + 1 disks, take the graph of h disks and replace each small triangle with the graph for two disks.

For three disks the graph is:

The game graph of level 7 shows the relatedness to the Sierpiński triangle.
  • call the pegs a, b, and c
  • list disk positions from left to right in order of increasing size

The sides of the outermost triangle represent the shortest ways of moving a tower from one peg to another one. The edge in the middle of the sides of the largest triangle represents a move of the largest disk. The edge in the middle of the sides of each next smaller triangle represents a move of each next smaller disk. The sides of the smallest triangles represent moves of the smallest disk.

In general, for a puzzle with n disks, there are 3n nodes in the graph; every node has three edges to other nodes, except the three corner nodes, which have two: it is always possible to move the smallest disk to one of the two other pegs, and it is possible to move one disk between those two pegs except in the situation where all disks are stacked on one peg. The corner nodes represent the three cases where all the disks are stacked on one peg. The diagram for n + 1 disks is obtained by taking three copies of the n-disk diagram—each one representing all the states and moves of the smaller disks for one particular position of the new largest disk—and joining them at the corners with three new edges, representing the only three opportunities to move the largest disk. The resulting figure thus has 3n+1 nodes and still has three corners remaining with only two edges.

As more disks are added, the graph representation of the game will resemble a fractal figure, the Sierpiński triangle. It is clear that the great majority of positions in the puzzle will never be reached when using the shortest possible solution; indeed, if the priests of the legend are using the longest possible solution (without re-visiting any position), it will take them 364 − 1 moves, or more than 1023 years.

The longest non-repetitive way for three disks can be visualized by erasing the unused edges:

Incidentally, this longest non-repetitive path can be obtained by forbidding all moves from a to c.

The Hamiltonian cycle for three disks is:

The graphs clearly show that:

  • From every arbitrary distribution of disks, there is exactly one shortest way to move all disks onto one of the three pegs.
  • Between every pair of arbitrary distributions of disks there are one or two different shortest paths.
  • From every arbitrary distribution of disks, there are one or two different longest non-self-crossing paths to move all disks to one of the three pegs.
  • Between every pair of arbitrary distributions of disks there are one or two different longest non-self-crossing paths.
  • Let Nh be the number of non-self-crossing paths for moving a tower of h disks from one peg to another one. Then:
    • N1 = 2
    • Nh+1 = (Nh)2 + (Nh)3

This gives Nh to be 2, 12, 1872, 6563711232, ... (sequence A125295 in the OEIS)

Variations

[edit]

Linear Hanoi

[edit]

If all moves must be between adjacent pegs (i.e. given pegs A, B, C, one cannot move directly between pegs A and C), then moving a stack of n disks from peg A to peg C takes 3n − 1 moves. The solution uses all 3n valid positions, always taking the unique move that does not undo the previous move. The position with all disks at peg B is reached halfway, i.e. after (3n − 1) / 2 moves.[17][18]

Cyclic Hanoi

[edit]

In Cyclic Hanoi, we are given three pegs (A, B, C), which are arranged as a circle with the clockwise and the counterclockwise directions being defined as A – B – C – A and A – C – B – A, respectively. The moving direction of the disk must be clockwise.[19] It suffices to represent the sequence of disks to be moved. The solution can be found using two mutually recursive procedures:

To move n disks counterclockwise to the neighbouring target peg:

  1. move n − 1 disks counterclockwise to the target peg
  2. move disk #n one step clockwise
  3. move n − 1 disks clockwise to the start peg
  4. move disk #n one step clockwise
  5. move n − 1 disks counterclockwise to the target peg

To move n disks clockwise to the neighbouring target peg:

  1. move n − 1 disks counterclockwise to a spare peg
  2. move disk #n one step clockwise
  3. move n − 1 disks counterclockwise to the target peg

Let C(n) and A(n) represent moving n disks clockwise and counterclockwise, then we can write down both formulas:

C(n) = A(n−1) n A(n−1) and A(n) = A(n−1) n C(n−1) n A(n−1).
Thus C(1) = 1 and A(1) = 1 1,
C(2) = 1 1 2 1 1 and A(2) = 1 1 2 1 2 1 1.

The solution for the Cyclic Hanoi has some interesting properties:

  1. The move-patterns of transferring a tower of disks from a peg to another peg are symmetric with respect to the center points.
  2. The smallest disk is the first and last disk to move.
  3. Groups of the smallest disk moves alternate with single moves of other disks.
  4. The number of disks moves specified by C(n) and A(n) are minimal.

With four pegs and beyond

[edit]

Although the three-peg version has a simple recursive solution long been known, the optimal solution for the Tower of Hanoi problem with four pegs (called Reve's puzzle) was not verified until 2014, by Bousch.[20]

However, in case of four or more pegs, the Frame–Stewart algorithm is known without proof of optimality since 1941.[21]

For the formal derivation of the exact number of minimal moves required to solve the problem by applying the Frame–Stewart algorithm (and other equivalent methods), see the following paper.[22]

For other variants of the four-peg Tower of Hanoi problem, see Paul Stockmeyer's survey paper.[23]

The so-called Towers of Bucharest and Towers of Klagenfurt game configurations yield ternary and pentary Gray codes.[24]

Frame–Stewart algorithm

[edit]

The Frame–Stewart algorithm is described below:

  • Let be the number of disks.
  • Let be the number of pegs.
  • Define to be the minimum number of moves required to transfer n disks using r pegs.

The algorithm can be described recursively:

  1. For some , , transfer the top disks to a single peg other than the start or destination pegs, taking moves.
  2. Without disturbing the peg that now contains the top disks, transfer the remaining disks to the destination peg, using only the remaining pegs, taking moves.
  3. Finally, transfer the top disks to the destination peg, taking moves.

The entire process takes moves. Therefore, the count should be picked for which this quantity is minimum. In the 4-peg case, the optimal equals , where is the nearest integer function.[25] For example, in the UPenn CIS 194 course on Haskell, the first assignment page[26] lists the optimal solution for the 15-disk and 4-peg case as 129 steps, which is obtained for the above value of k.

This algorithm is presumed to be optimal for any number of pegs; its number of moves is 2Θ(n1/(r−2)) (for fixed r).

General shortest paths and the number 466/885

[edit]

A curious generalization of the original goal of the puzzle is to start from a given configuration of the disks where all disks are not necessarily on the same peg and to arrive in a minimal number of moves at another given configuration. In general, it can be quite difficult to compute a shortest sequence of moves to solve this problem. A solution was proposed by Andreas Hinz and is based on the observation that in a shortest sequence of moves, the largest disk that needs to be moved (obviously one may ignore all of the largest disks that will occupy the same peg in both the initial and final configurations) will move either exactly once or exactly twice.

The mathematics related to this generalized problem becomes even more interesting when one considers the average number of moves in a shortest sequence of moves between two initial and final disk configurations that are chosen at random. Hinz and Chan Tat-Hung independently discovered[27][28] (see also [29]: Chapter 1, p. 14 ) that the average number of moves in an n-disk Tower is given by the following exact formula:

For large enough n, only the first and second terms do not converge to zero, so we get an asymptotic expression: , as . Thus intuitively, we could interpret the fraction of as representing the ratio of the labor one has to perform when going from a randomly chosen configuration to another randomly chosen configuration, relative to the difficulty of having to cross the "most difficult" path of length which involves moving all the disks from one peg to another. An alternative explanation for the appearance of the constant 466/885, as well as a new and somewhat improved algorithm for computing the shortest path, was given by Romik.[30]

Magnetic Hanoi

[edit]

In Magnetic Tower of Hanoi, each disk has two distinct sides North and South (typically colored "red" and "blue"). Disks must not be placed with the similar poles together—magnets in each disk prevent this illegal move. Also, each disk must be flipped as it is moved.

Initial configuration of bicolor Towers of Hanoi (n=4)

Bicolor Towers of Hanoi

[edit]

This variation of the famous Tower of Hanoi puzzle was offered to grade 3–6 students at 2ème Championnat de France des Jeux Mathématiques et Logiques held in July 1988.[31]

Final configuration of bicolor Towers of Hanoi (n=4)

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. The goal of the puzzle is to make the towers monochrome (same color). The biggest disks at the bottom of the towers are assumed to swap positions.

Tower of Hanoy

[edit]

A variation of the puzzle has been adapted as a solitaire game with nine playing cards under the name Tower of Hanoy.[32][33] It is not known whether the altered spelling of the original name is deliberate or accidental.[34]

Applications

[edit]
3D AFM topographic image of multilayered palladium nanosheet on silicon wafer, with Tower of Hanoi-like structure.[35]

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 disorders of executive function.[36]

Zhang and Norman[37] used several isomorphic (equivalent) representations of the game to study the impact of representational effect in task design. They demonstrated an impact on user performance by changing the way that the rules of the game are represented, using variations in the physical design of the game components. This knowledge has impacted on the development of the TURF framework[38] for the representation of human–computer interaction.

The Tower of Hanoi is also used as a backup rotation scheme when performing computer data backups where multiple tapes/media are involved.[39]

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.[citation needed]

The Tower of Hanoi is also used as a test by neuropsychologists trying to evaluate frontal lobe deficits.[40]

In 2010, researchers published the results of an experiment that found that the ant species Linepithema humile were successfully able to solve the 3-disk version of the Tower of Hanoi problem through non-linear dynamics and pheromone signals.[41]

In 2014, scientists synthesized multilayered palladium nanosheets with a Tower of Hanoi-like structure.[35]

[edit]

In the science fiction story "Now Inhale", by Eric Frank Russell, a human is held prisoner on a planet where the local custom is to make the prisoner play a game until it is won or lost before his execution. The protagonist knows that a rescue ship might take a year or more to arrive, so he chooses to play Towers of Hanoi with 64 disks. This story makes reference to the legend about the Buddhist monks playing the game until the end of the world.[42][43][44]

In the 1966 Doctor Who story The Celestial Toymaker, the eponymous villain forces the Doctor to play a ten-piece, 1,023-move Tower of Hanoi game entitled The Trilogic Game with the pieces forming a pyramid shape when stacked.[43][45]

In 2007, the concept of the Towers Of Hanoi problem was used in Professor Layton and the Diabolical Box in puzzles 6, 83, and 84, but the disks had been changed to pancakes. The puzzle was based around a dilemma where the chef of a restaurant had to move a pile of pancakes from one plate to the other with the basic principles of the original puzzle (i.e. three plates that the pancakes could be moved onto, not being able to put a larger pancake onto a smaller one, etc.)

In the 2011 film Rise of the Planet of the Apes, this puzzle, called in the film the "Lucas Tower", is used as a test to study the intelligence of apes.[43]

The puzzle is featured regularly in adventure and puzzle games. Since it is easy to implement, and easily recognised, it is well suited to use as a puzzle in a larger graphical game (e.g. Star Wars: Knights of the Old Republic and Mass Effect).[46] Some implementations use straight disks, but others disguise the puzzle in some other form. There is an arcade version by Sega.[47]

A 15-disk version of the puzzle appears in the game Sunless Sea as a lock to a tomb. The player has the option to click through each move of the puzzle in order to solve it, but the game notes that it will take 32,767 moves to complete. If an especially dedicated player does click through to the end of the puzzle, it is revealed that completing the puzzle does not unlock the door.

This was first used as a challenge in Survivor Thailand in 2002 but rather than rings, the pieces were made to resemble a temple. Sook Jai threw the challenge to get rid of Jed even though Shii-Ann knew full well how to complete the puzzle. The problem is featured as part of a reward challenge in a 2011 episode of the American version of the Survivor TV series. Both players (Ozzy Lusth and Benjamin "Coach" Wade) struggled to understand how to solve the puzzle and are aided by their fellow tribe members.

In Genshin Impact, this puzzle is shown in Faruzan's hangout quest, "Early Learning Mechanism", where she mentions seeing it as a mechanism and uses it to make a toy prototype for children. She calls it pagoda stacks.

See also

[edit]

Notes

[edit]
  1. ^ "A000225 - OEIS". oeis.org. Retrieved 2021-09-03.
  2. ^ Hofstadter, Douglas R. (1985). Metamagical Themas : Questing for the Essence of Mind and Pattern. New York: Basic Books. ISBN 978-0-465-04540-2.
  3. ^ Cohn, Ernst M. (1963). "A device for demonstrating some elementary properties of integers". The Mathematics Teacher. 56 (2). National Council of Teachers of Mathematics: 84. doi:10.5951/MT.56.2.0084. ISSN 0025-5769. Retrieved 9 March 2021.
  4. ^ Weisstein, Eric W. "Tower of Hanoi". mathworld.wolfram.com. Retrieved 2023-10-20.
  5. ^ a b Hinz, Andreas M.; Klavžar, Sandi; Milutinović, Uroš; Petr, Ciril (2013-01-31). The Tower of Hanoi – Myths and Maths. Springer. ISBN 978-3034802369.
  6. ^ Stockmeyer, Paul K. "The Tower of Hanoi: A Bibliography" (PDF). Retrieved 2024-02-21.
  7. ^ de Parville, Henri (1883-12-27). "Revue des Sciences". Journal des débats. Retrieved 2024-02-21.
  8. ^ Lucas, Édouard (1889). Jeux scientifiques pour servir à l'histoire, à l'enseignement et à la pratique du calcul et du dessin (in French). Paris: Chambon et Baye. Retrieved 2024-01-27.
  9. ^ Lucas, Édouard (1892). Récréations mathématiques (in French). Vol. 3. Librairie Albert Blanchard, 1979. p. 58.
  10. ^ Stockmeyer, Paul K. "Tower of Hanoi instructions in English, page 1". Retrieved 2024-02-21.
  11. ^ Moscovich, Ivan (2001). 1000 playthinks: puzzles, paradoxes, illusions & games. Workman. ISBN 978-0-7611-1826-8.
  12. ^ Petković, Miodrag (2009). Famous Puzzles of Great Mathematicians. AMS Bookstore. p. 197. ISBN 978-0-8218-4814-2.
  13. ^ Troshkin, M. "Doomsday Comes: A Nonrecursive Analysis of the Recursive Towers-of-Hanoi Problem". Focus (in Russian). 95 (2): 10–14.
  14. ^ Warren, Henry S. (2003). "Section 5-4: Counting Trailing 0's.". Hacker's delight (1st ed.). Boston MA: Addison-Wesley. ISBN 978-0-201-91465-8.
  15. ^ Miller, Charles D. (2000). "Ch. 4: Binary Numbers and the Standard Gray Code". Mathematical Ideas (9 ed.). Addison Wesley Longman. ISBN 978-0-321-07607-6. Archived from the original on 2004-08-21.
  16. ^ Gros, L. (1872). Théorie du Baguenodier. Lyon: Aimé Vingtrinier.
  17. ^ "Question Corner -- Generalizing the Towers of Hanoi Problem". math.toronto.edu. Retrieved 2023-07-28.
  18. ^ Hinz, Andreas M.; Klavzar, Sandi; Milutinovic, Uros; Petr, Ciril; Stewart, Ian (2013). The Tower of Hanoi – Myths and Maths (1st ed.). Basel: Springer Science+Business Media. pp. 241–259. ISBN 9783034802369.
  19. ^ Gedeon, T. D. (1996). "The Cyclic Towers of Hanoi: An Iterative Solution Produced by Transformation". The Computer Journal. 39 (4): 353–356. doi:10.1093/comjnl/39.4.353.
  20. ^ Bousch, T. (2014). "La quatrieme tour de Hanoi" (PDF). Bull. Belg. Math. Soc. Simon Stevin. 21 (5): 895–912. doi:10.36045/bbms/1420071861. S2CID 14243013. Archived from the original (PDF) on 2017-09-21.
  21. ^ Stewart, B. M.; Frame, J. S. (March 1941). "Solution to advanced problem 3819". American Mathematical Monthly. 48 (3): 216–9. doi:10.2307/2304268. JSTOR 2304268.
  22. ^ Klavzar, Sandi; Milutinovi, Uro; Petrb, Ciril (2002). "Variations on the Four-Post Tower of Hanoi Puzzle" (Postscript). Congressus Numerantium. 102.
  23. ^ Stockmeyer, Paul (1994). "Variations on the Four-Post Tower of Hanoi Puzzle" (Postscript). Congressus Numerantium. 102: 3–12.
  24. ^ Herter, Felix; Rote, Günter (2018-11-14) [2018-08-09, 2017-12, 2017-08-09, 2016-04-22]. "Loopless Gray Code Enumeration and the Tower of Bucharest" (PDF). Theoretical Computer Science. 748. Berlin, Germany: 40–54. arXiv:1604.06707. doi:10.1016/j.tcs.2017.11.017. ISSN 0304-3975. S2CID 4014870. Archived (PDF) from the original on 2020-12-16. Retrieved 2020-12-16. [1] (15/18/19/24 pages)
  25. ^ "University of Toronto CSC148 Slog". April 5, 2014. Retrieved July 22, 2015.
  26. ^ "UPenn CIS 194 Introduction to Haskell Assignment 1" (PDF). Retrieved January 31, 2016.
  27. ^ Hinz, A. (1989). "The Tower of Hanoi". L'Enseignement Mathématique. 35: 289–321. doi:10.5169/seals-57378.
  28. ^ Chan, T. (1988). "A statistical analysis of the towers of Hanoi problem". Internat. J. Comput. Math. 28 (1–4): 57–65. doi:10.1080/00207168908803728.
  29. ^ Stewart, Ian (2004). Another Fine Math You've Got Me Into... Courier Dover. ISBN 978-0-7167-2342-4.
  30. ^ Romik, D. (2006). "Shortest paths in the Tower of Hanoi graph and finite automata". SIAM Journal on Discrete Mathematics. 20 (3): 610–622. arXiv:math/0310109. doi:10.1137/050628660. S2CID 8342396.
  31. ^ Prasad Vithal Chaugule (2015). "A Recursive Solution to Bicolor Towers of Hanoi Problem" (PDF). Recreational Mathematics Magazine (4): 37–48. ISSN 2182-1976.
  32. ^ Arnold, Peter (2003-05-28). Card Games for One. Sterling Publishing Company. ISBN 978-0-600-60727-4.
  33. ^ Hedges, Sid G. (2018-03-06). Everybody's Book of Hobbies. Read Books Ltd. ISBN 978-1-5287-8344-6.
  34. ^ "Tower Of Hanoy Patience (AKA Tower Of Hanoi Patience)". bbcmicro.co.uk. Retrieved 2020-10-17.
  35. ^ a b Yin, Xi; Liu, Xinhong; Pan, Yung-Tin; Walsh, Kathleen A.; Yang, Hong (November 4, 2014). "Hanoi Tower-like Multilayered Ultrathin Palladium Nanosheets". Nano Letters. 14 (12): 7188–94. Bibcode:2014NanoL..14.7188Y. doi:10.1021/nl503879a. PMID 25369350.
  36. ^ Shallice, T. (1982-06-25). "Specific impairments of planning". Philosophical Transactions of the Royal Society of London. B, Biological Sciences. 298 (1089): 199–209. Bibcode:1982RSPTB.298..199S. doi:10.1098/rstb.1982.0082. ISSN 0080-4622. PMID 6125971.
  37. ^ Zhang, J (1994). "Representations in distributed cognitive tasks" (PDF). Cognitive Science. 18: 87–122. doi:10.1016/0364-0213(94)90021-3.
  38. ^ Zhang, Jiajie; Walji, Muhammad F. (2011). "TURF: Toward a unified framework of EHR usability". Journal of Biomedical Informatics. 44 (6): 1056–67. doi:10.1016/j.jbi.2011.08.005. PMID 21867774.
  39. ^ Ruiz, Dirk; Newell, Allen (1989-06-01). Tower-Noticing Triggers Strategy-Change in the Tower of Hanoi: A Soar Model (Report). Fort Belvoir, VA: Defense Technical Information Center.
  40. ^ Beers, S. R.; Rosenberg, D. R.; Dick, E. L.; Williams, T.; O'Hearn, K. M.; Birmaher, B.; Ryan, C. M. (1999). "Neuropsychological study of frontal lobe function in psychotropic-naive children with obsessive-compulsive disorder". The American Journal of Psychiatry. 156 (5): 777–9. doi:10.1176/ajp.156.5.777. PMID 10327915. S2CID 21359382.
  41. ^ Reid, C.R.; Sumpter, D.J.; Beekman, M. (January 2011). "Optimisation in a natural system: Argentine ants solve the Towers of Hanoi". J. Exp. Biol. 214 (Pt 1): 50–8. CiteSeerX 10.1.1.231.9201. doi:10.1242/jeb.048173. PMID 21147968. S2CID 18819977.
  42. ^ Russell, Eric Frank (April 1959). "Now Inhale". Novelettes. Astounding Science Fiction. Vol. 63, no. 2. pp. 31–77.
    • Reprinted: Russell, Eric Frank (2000). "Now Inhale". In Katze, Rick (ed.). Major Ingredients: The Selected Short Stories of Eric Frank Russell. Framingham, Mass.: NESFA Press. pp. 399–417. ISBN 978-1-886778-10-8.
  43. ^ a b c Bonanome, Marianna C.; Dean, Margaret H.; Dean, Judith Putnam (2018). "Self-Similar Groups". A Sampling of Remarkable Groups: Thompson's, Self-similar, Lamplighter, and Baumslag-Solitar. Compact Textbooks in Mathematics. Cham, Switzerland: Springer. p. 96. doi:10.1007/978-3-030-01978-5_3. ISBN 978-3-030-01976-1.
  44. ^ Birtwistle, Graham (January 1985). "The coroutines of Hanoi". ACM SIGPLAN Notices. 20 (1): 9–10. doi:10.1145/988284.988286. S2CID 7310661.
  45. ^ "The Fourth Dimension: The Celestial Toymaker". Doctor Who. BBC One. Retrieved April 2, 2021.
  46. ^ "Tower of Hanoi (video game concept)". Giantbomb.com. Retrieved 2010-12-05.
  47. ^ "Tower of Hanoi / Andamiro". Sega Amusements. Archived from the original on 2012-03-01. Retrieved 2012-02-26.
[edit]