SlideShare a Scribd company logo
1 of 7
In 1883, Edouard Lucas invented, or perhaps reinvented, one of the most popular puzzles of all times - the Tower of Hanoi, as he called it - which is still used today in many computer science textbooks to demonstrate how to write a recursive algorithm or program. First of all, we will make a list of the rules of the puzzle: <br />There are three pegs: A, B and C. <br />There are n disks. The number n is constant while working the puzzle. <br />All disks are different in size. <br />The disks are initially stacked on peg A so that they increase in size from the top to the bottom. <br />The goal of the puzzle is to transfer the entire tower from the A peg to one of the others pegs. <br />One disk at a time can be moved from the top of a stack either to an empty peg or to a peg with a larger disk than itself on the top of its stack. <br />The Algorithm<br />It is well known and rather easy to prove that the minimum number of moves needed to complete the puzzle with n disks is . A simple algorithm which allows us to reach this optimum is as follows: for odd moves, take the smallest disk (number 1) from the peg where it lies to the next one in the circular sequence; for even moves, make the only possible move not involving disk 1. <br />Simple solution<br />The following solution is a simple solution for the toy puzzle.<br />Alternate moves between the smallest piece and a non-smallest piece. When moving the smallest piece, always move it in the same direction (to the right if the starting number of pieces is even, to the left if the starting number of pieces is odd). If there is no tower in the chosen direction, move the piece to the opposite end, but then continue to move in the correct direction. For example, if you started with three pieces, you would move the smallest piece to the opposite end, then continue in the left direction after that. When the turn is to move the non-smallest piece, there is only one legal move. Doing this should complete the puzzle using the least amount of moves to do so.<br />Recursive solution<br />A key to solving this puzzle is to recognize that it can be solved by breaking the problem down into a collection of smaller problems and further breaking those problems down into even smaller problems until a solution is reached. The following procedure demonstrates this approach.<br />label the pegs A, B, C—these labels may move at different steps <br />let n be the total number of discs <br />number the discs from 1 (smallest, topmost) to n (largest, bottommost) <br />To move n discs from peg A to peg C:<br />move n−1 discs from A to B. This leaves disc #n alone on peg A <br />move disc #n from A to C <br />move n−1 discs from B to C so they sit on disc #n <br />The above is a recursive algorithm: to carry out steps 1 and 3, apply the same algorithm again for n−1. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1. This step, moving a single disc from peg A to peg B, is trivial.<br />Non-recursive solution<br />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.<br />In alternate moves:<br />move the smallest disk to the peg it has not recently come from. <br />move another disk legally (there will be one possibility only) <br />For the very first move, the smallest disk goes to peg t if h is odd and to peg r if h is even.<br />Also observe that:<br />Disks whose ordinals have even parity move in the same sense as the smallest disk. <br />Disks whose ordinals have odd parity move in opposite sense. <br />If h is even, the remaining third peg during successive moves is t, r, f, t, r, f, etc. <br />If h is odd, the remaining third peg during successive moves is r, t, f, r, t, f, etc. <br />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:<br />Call the moves detailed above a disk's 'natural' move. <br />Examine the smallest top disk that is not disk 0, and note what it's only (legal) move would be: (if there is no such disc, then we are either at the first or last move). <br />If that move is the disk's 'natural' move, then the disc has not been moved since the last disc 0 move, and that move should be taken. <br />If that move is not the disk's 'natural' move, then move disk 0. <br />Binary solutions<br />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 #2n−1, with all digits 1), using the following rules:<br />There is one binary digit (bit) for each disk <br />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. <br />The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk. <br />A bit with the same value as the previous one means that the corresponding disk is stacked on top the previous disk on the same peg. <br />(That is to say: a straight sequence of 1's or 0's means that the corresponding disks are all on the same peg). <br />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: <br />Assume that the initial peg is on the left and the final peg is on the right. <br />Also assume quot;
wrappingquot;
 - so the right peg counts as one peg quot;
leftquot;
 of the left peg, and vice versa. <br />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 left, if n is odd, the disk located one peg to the right. <br />For example, in an 8-disk Hanoi:<br />Move 0 <br />The largest disk is 0, so it is on the left (initial) peg. <br />All other disks are 0 as well, so they are stacked on top of it. Hence all disks are on the initial peg. <br />Move 28-1 <br />The largest disk is 1, so it is on the right (final) peg. <br />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. <br />Move 0b11011000 = 21610 <br />The largest disk is 1, so it is on the right (final) peg. <br />Disk two is also 1, so it is stacked on top of it, on the right peg. <br />Disk three is 0, so it is on another peg. Since n is odd, it is one peg to the right, i.e. on the left peg. <br />Disk four is 1, so it is on another peg. Since n is still even, it is one peg to the left, i.e. on the right peg. <br />Disk five is also 1, so it is stacked on top of it, on the right peg. <br />Disk six is 0, so it is on another peg. Since n is even, the disk is one peg to the left, i.e. on the middle peg. <br />Disks seven and eight are also 0, so they are stacked on top of it, on the middle peg. <br />Graphical representation<br />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:<br />The graph for 2 disks is 3 triangles arranged in a larger triangle:<br />The nodes at the vertices of the outermost triangle represent distributions with all disks on the same peg.<br />For h+1 disks, take the graph of h disks and replace each small triangle with the graph for 2 disks.<br />For 3 disks the graph is:<br />call the pegs a, b and c <br />list disk positions from left to right in order of increasing size <br />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.<br />The game graph of level 7 shows the relatedness to the Sierpiński Triangle<br />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 the 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.<br />As more disks are added, the graph representation of the game will resemble the Fractal figure, 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.<br />The longest non-repetitive way for three disks can be visualized by erasing the unused edges:<br />The circular Hamiltonian path for three disks is:<br />The graphs clearly show that:<br />From every arbitrary distribution of disks, there is exactly one shortest way to move all disks onto one of the three pegs. <br />Between every pair of arbitrary distributions of disks there are one or two different shortest paths. <br />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. <br />Between every pair of arbitrary distributions of disks there are one or two different longest non selfcrossing paths. <br />Let Nh be the number of non selfcrossing paths for moving a tower of h disks from one peg to another one. Then: <br />N1=2 <br />Nh+1=(Nh)2+(Nh)3. <br />For example: N8≈1.5456x10795 <br />Applications<br />The Tower of Hanoi is frequently used in psychological research on problem solving. There also exists a variant of this task called Tower of London for neuropsychological diagnosis and treatment of executive functions.<br />The Tower of Hanoi is also used as Backup rotation scheme when performing computer data Backups where multiple tapes/media are involved.<br />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.<br />The Tower of Hanoi is also used as a test by neuropsychologists trying to evaluate frontal lobe deficits.<br /> <br />
Tower of hanoi
Tower of hanoi
Tower of hanoi
Tower of hanoi
Tower of hanoi
Tower of hanoi

More Related Content

What's hot

267258402 heat-4e-chap03-lecture
267258402 heat-4e-chap03-lecture267258402 heat-4e-chap03-lecture
267258402 heat-4e-chap03-lectureFahad Gmail Gmail
 
Fraction Review
Fraction ReviewFraction Review
Fraction ReviewLauren
 
Direct, inverse, and partitive proportions
Direct, inverse, and partitive proportionsDirect, inverse, and partitive proportions
Direct, inverse, and partitive proportionsNecolleSario
 
Volume of Cubes and Cuboid
Volume of Cubes and CuboidVolume of Cubes and Cuboid
Volume of Cubes and Cuboidangbeelee
 
Data Gathering and Data Organization (Intro to Mathematics in the Modern World)
Data Gathering and Data Organization (Intro to Mathematics in the Modern World)Data Gathering and Data Organization (Intro to Mathematics in the Modern World)
Data Gathering and Data Organization (Intro to Mathematics in the Modern World)Michael Angelo Manlapaz
 
Sight Distance for horizontal curves
Sight Distance for horizontal curvesSight Distance for horizontal curves
Sight Distance for horizontal curvesLatif Hyder Wadho
 
Adding and Subtracting Improper Fractions
Adding and Subtracting Improper FractionsAdding and Subtracting Improper Fractions
Adding and Subtracting Improper Fractionscaitlinlouiseevans
 
impact of jet on curved plate
impact of jet on curved plateimpact of jet on curved plate
impact of jet on curved plateRathod Mehul
 
Q Week 5 - CHANGING FRACTION TO DECIMAL AND VICE VERSA.pptx
Q Week 5 - CHANGING FRACTION TO DECIMAL AND VICE VERSA.pptxQ Week 5 - CHANGING FRACTION TO DECIMAL AND VICE VERSA.pptx
Q Week 5 - CHANGING FRACTION TO DECIMAL AND VICE VERSA.pptxErwinJoaquinCabigao
 

What's hot (13)

267258402 heat-4e-chap03-lecture
267258402 heat-4e-chap03-lecture267258402 heat-4e-chap03-lecture
267258402 heat-4e-chap03-lecture
 
Ratios And Rates
Ratios And RatesRatios And Rates
Ratios And Rates
 
Fraction Review
Fraction ReviewFraction Review
Fraction Review
 
Decision making
Decision makingDecision making
Decision making
 
Direct, inverse, and partitive proportions
Direct, inverse, and partitive proportionsDirect, inverse, and partitive proportions
Direct, inverse, and partitive proportions
 
Calculus III
Calculus IIICalculus III
Calculus III
 
Volume of Cubes and Cuboid
Volume of Cubes and CuboidVolume of Cubes and Cuboid
Volume of Cubes and Cuboid
 
Data Gathering and Data Organization (Intro to Mathematics in the Modern World)
Data Gathering and Data Organization (Intro to Mathematics in the Modern World)Data Gathering and Data Organization (Intro to Mathematics in the Modern World)
Data Gathering and Data Organization (Intro to Mathematics in the Modern World)
 
Dividing Fractions
Dividing FractionsDividing Fractions
Dividing Fractions
 
Sight Distance for horizontal curves
Sight Distance for horizontal curvesSight Distance for horizontal curves
Sight Distance for horizontal curves
 
Adding and Subtracting Improper Fractions
Adding and Subtracting Improper FractionsAdding and Subtracting Improper Fractions
Adding and Subtracting Improper Fractions
 
impact of jet on curved plate
impact of jet on curved plateimpact of jet on curved plate
impact of jet on curved plate
 
Q Week 5 - CHANGING FRACTION TO DECIMAL AND VICE VERSA.pptx
Q Week 5 - CHANGING FRACTION TO DECIMAL AND VICE VERSA.pptxQ Week 5 - CHANGING FRACTION TO DECIMAL AND VICE VERSA.pptx
Q Week 5 - CHANGING FRACTION TO DECIMAL AND VICE VERSA.pptx
 

Viewers also liked

Towers Hanoi Algorithm
Towers Hanoi AlgorithmTowers Hanoi Algorithm
Towers Hanoi AlgorithmJorge Jasso
 
Algorithmic puzzles - #83 restricted tower of hanoi
Algorithmic puzzles - #83  restricted tower of hanoiAlgorithmic puzzles - #83  restricted tower of hanoi
Algorithmic puzzles - #83 restricted tower of hanoiNicholas Chen
 
towers of hanoi
towers of hanoitowers of hanoi
towers of hanoistudent
 
Araling Panlipunan Grade 8 - First Quarter Module
Araling Panlipunan Grade 8 - First Quarter ModuleAraling Panlipunan Grade 8 - First Quarter Module
Araling Panlipunan Grade 8 - First Quarter ModuleJhing Pantaleon
 

Viewers also liked (10)

Tower of hanoi
Tower of hanoiTower of hanoi
Tower of hanoi
 
Tower of Hanoi
Tower of HanoiTower of Hanoi
Tower of Hanoi
 
Towers Hanoi Algorithm
Towers Hanoi AlgorithmTowers Hanoi Algorithm
Towers Hanoi Algorithm
 
Tower of Hanoi
Tower of HanoiTower of Hanoi
Tower of Hanoi
 
Algorithmic puzzles - #83 restricted tower of hanoi
Algorithmic puzzles - #83  restricted tower of hanoiAlgorithmic puzzles - #83  restricted tower of hanoi
Algorithmic puzzles - #83 restricted tower of hanoi
 
Tower of hanoi
Tower of hanoiTower of hanoi
Tower of hanoi
 
towers of hanoi
towers of hanoitowers of hanoi
towers of hanoi
 
Tower of hanoi
Tower of hanoiTower of hanoi
Tower of hanoi
 
AP G8/G9 lm q1
AP G8/G9 lm q1AP G8/G9 lm q1
AP G8/G9 lm q1
 
Araling Panlipunan Grade 8 - First Quarter Module
Araling Panlipunan Grade 8 - First Quarter ModuleAraling Panlipunan Grade 8 - First Quarter Module
Araling Panlipunan Grade 8 - First Quarter Module
 

Similar to Tower of hanoi

Tower of hanoi algorithm
Tower of hanoi algorithmTower of hanoi algorithm
Tower of hanoi algorithmWeaamRaed
 
Data Structure and Algorithms The Tower of Hanoi
Data Structure and Algorithms The Tower of HanoiData Structure and Algorithms The Tower of Hanoi
Data Structure and Algorithms The Tower of HanoiManishPrajapati78
 
Tower of Hanoi presentation
Tower of Hanoi presentationTower of Hanoi presentation
Tower of Hanoi presentationFahadQaiser1
 
Newton's Second Law - The Effect of Force
Newton's Second Law - The Effect of ForceNewton's Second Law - The Effect of Force
Newton's Second Law - The Effect of ForceSarah Sue Calbio
 
AI-Lec3 State Search Space-Graph Theory.pptx
AI-Lec3 State Search Space-Graph Theory.pptxAI-Lec3 State Search Space-Graph Theory.pptx
AI-Lec3 State Search Space-Graph Theory.pptxSeharAli13
 
ACM ICPC 2013 NEERC (Northeastern European Regional Contest) Problems Review
ACM ICPC 2013 NEERC (Northeastern European Regional Contest) Problems ReviewACM ICPC 2013 NEERC (Northeastern European Regional Contest) Problems Review
ACM ICPC 2013 NEERC (Northeastern European Regional Contest) Problems ReviewRoman Elizarov
 
homework_chap_3_a_solutions.docx
homework_chap_3_a_solutions.docxhomework_chap_3_a_solutions.docx
homework_chap_3_a_solutions.docxtsrtgsdfg
 
Recurrent Problem in Discrete Mathmatics.pptx
Recurrent Problem in Discrete Mathmatics.pptxRecurrent Problem in Discrete Mathmatics.pptx
Recurrent Problem in Discrete Mathmatics.pptxgbikorno
 
100 Combinatorics Problems (With Solutions)
100 Combinatorics Problems (With Solutions)100 Combinatorics Problems (With Solutions)
100 Combinatorics Problems (With Solutions)Courtney Esco
 
Fundamentals of Physics (MOTION ALONG A STRAIGHT LINE)
Fundamentals of Physics (MOTION ALONG A STRAIGHT LINE)Fundamentals of Physics (MOTION ALONG A STRAIGHT LINE)
Fundamentals of Physics (MOTION ALONG A STRAIGHT LINE)Muhammad Faizan Musa
 
Recurrent problems: TOH, Pizza Cutting and Josephus Problems
Recurrent problems: TOH, Pizza Cutting and Josephus ProblemsRecurrent problems: TOH, Pizza Cutting and Josephus Problems
Recurrent problems: TOH, Pizza Cutting and Josephus ProblemsMenglinLiu1
 

Similar to Tower of hanoi (20)

Tower of hanoi algorithm
Tower of hanoi algorithmTower of hanoi algorithm
Tower of hanoi algorithm
 
Data Structure and Algorithms The Tower of Hanoi
Data Structure and Algorithms The Tower of HanoiData Structure and Algorithms The Tower of Hanoi
Data Structure and Algorithms The Tower of Hanoi
 
Stochastic Process Assignment Help
Stochastic Process Assignment HelpStochastic Process Assignment Help
Stochastic Process Assignment Help
 
Stochastic Process Exam Help
Stochastic Process Exam HelpStochastic Process Exam Help
Stochastic Process Exam Help
 
Data structure lab
Data structure labData structure lab
Data structure lab
 
Tower of Hanoi presentation
Tower of Hanoi presentationTower of Hanoi presentation
Tower of Hanoi presentation
 
Newton's Second Law - The Effect of Force
Newton's Second Law - The Effect of ForceNewton's Second Law - The Effect of Force
Newton's Second Law - The Effect of Force
 
AI-Lec3 State Search Space-Graph Theory.pptx
AI-Lec3 State Search Space-Graph Theory.pptxAI-Lec3 State Search Space-Graph Theory.pptx
AI-Lec3 State Search Space-Graph Theory.pptx
 
Tower of Hanoi
Tower of HanoiTower of Hanoi
Tower of Hanoi
 
ACM ICPC 2013 NEERC (Northeastern European Regional Contest) Problems Review
ACM ICPC 2013 NEERC (Northeastern European Regional Contest) Problems ReviewACM ICPC 2013 NEERC (Northeastern European Regional Contest) Problems Review
ACM ICPC 2013 NEERC (Northeastern European Regional Contest) Problems Review
 
homework_chap_3_a_solutions.docx
homework_chap_3_a_solutions.docxhomework_chap_3_a_solutions.docx
homework_chap_3_a_solutions.docx
 
Pascal Triangle
Pascal TrianglePascal Triangle
Pascal Triangle
 
Recurrent Problem in Discrete Mathmatics.pptx
Recurrent Problem in Discrete Mathmatics.pptxRecurrent Problem in Discrete Mathmatics.pptx
Recurrent Problem in Discrete Mathmatics.pptx
 
100 Combinatorics Problems (With Solutions)
100 Combinatorics Problems (With Solutions)100 Combinatorics Problems (With Solutions)
100 Combinatorics Problems (With Solutions)
 
Fundamentals of Physics (MOTION ALONG A STRAIGHT LINE)
Fundamentals of Physics (MOTION ALONG A STRAIGHT LINE)Fundamentals of Physics (MOTION ALONG A STRAIGHT LINE)
Fundamentals of Physics (MOTION ALONG A STRAIGHT LINE)
 
Blindfold
BlindfoldBlindfold
Blindfold
 
On reflection
On reflection On reflection
On reflection
 
Recurrent problems: TOH, Pizza Cutting and Josephus Problems
Recurrent problems: TOH, Pizza Cutting and Josephus ProblemsRecurrent problems: TOH, Pizza Cutting and Josephus Problems
Recurrent problems: TOH, Pizza Cutting and Josephus Problems
 
400 puzzlesnnn
400 puzzlesnnn400 puzzlesnnn
400 puzzlesnnn
 
Sol90
Sol90Sol90
Sol90
 

Recently uploaded

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 

Recently uploaded (20)

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 

Tower of hanoi

  • 1. In 1883, Edouard Lucas invented, or perhaps reinvented, one of the most popular puzzles of all times - the Tower of Hanoi, as he called it - which is still used today in many computer science textbooks to demonstrate how to write a recursive algorithm or program. First of all, we will make a list of the rules of the puzzle: <br />There are three pegs: A, B and C. <br />There are n disks. The number n is constant while working the puzzle. <br />All disks are different in size. <br />The disks are initially stacked on peg A so that they increase in size from the top to the bottom. <br />The goal of the puzzle is to transfer the entire tower from the A peg to one of the others pegs. <br />One disk at a time can be moved from the top of a stack either to an empty peg or to a peg with a larger disk than itself on the top of its stack. <br />The Algorithm<br />It is well known and rather easy to prove that the minimum number of moves needed to complete the puzzle with n disks is . A simple algorithm which allows us to reach this optimum is as follows: for odd moves, take the smallest disk (number 1) from the peg where it lies to the next one in the circular sequence; for even moves, make the only possible move not involving disk 1. <br />Simple solution<br />The following solution is a simple solution for the toy puzzle.<br />Alternate moves between the smallest piece and a non-smallest piece. When moving the smallest piece, always move it in the same direction (to the right if the starting number of pieces is even, to the left if the starting number of pieces is odd). If there is no tower in the chosen direction, move the piece to the opposite end, but then continue to move in the correct direction. For example, if you started with three pieces, you would move the smallest piece to the opposite end, then continue in the left direction after that. When the turn is to move the non-smallest piece, there is only one legal move. Doing this should complete the puzzle using the least amount of moves to do so.<br />Recursive solution<br />A key to solving this puzzle is to recognize that it can be solved by breaking the problem down into a collection of smaller problems and further breaking those problems down into even smaller problems until a solution is reached. The following procedure demonstrates this approach.<br />label the pegs A, B, C—these labels may move at different steps <br />let n be the total number of discs <br />number the discs from 1 (smallest, topmost) to n (largest, bottommost) <br />To move n discs from peg A to peg C:<br />move n−1 discs from A to B. This leaves disc #n alone on peg A <br />move disc #n from A to C <br />move n−1 discs from B to C so they sit on disc #n <br />The above is a recursive algorithm: to carry out steps 1 and 3, apply the same algorithm again for n−1. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1. This step, moving a single disc from peg A to peg B, is trivial.<br />Non-recursive solution<br />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.<br />In alternate moves:<br />move the smallest disk to the peg it has not recently come from. <br />move another disk legally (there will be one possibility only) <br />For the very first move, the smallest disk goes to peg t if h is odd and to peg r if h is even.<br />Also observe that:<br />Disks whose ordinals have even parity move in the same sense as the smallest disk. <br />Disks whose ordinals have odd parity move in opposite sense. <br />If h is even, the remaining third peg during successive moves is t, r, f, t, r, f, etc. <br />If h is odd, the remaining third peg during successive moves is r, t, f, r, t, f, etc. <br />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:<br />Call the moves detailed above a disk's 'natural' move. <br />Examine the smallest top disk that is not disk 0, and note what it's only (legal) move would be: (if there is no such disc, then we are either at the first or last move). <br />If that move is the disk's 'natural' move, then the disc has not been moved since the last disc 0 move, and that move should be taken. <br />If that move is not the disk's 'natural' move, then move disk 0. <br />Binary solutions<br />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 #2n−1, with all digits 1), using the following rules:<br />There is one binary digit (bit) for each disk <br />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. <br />The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk. <br />A bit with the same value as the previous one means that the corresponding disk is stacked on top the previous disk on the same peg. <br />(That is to say: a straight sequence of 1's or 0's means that the corresponding disks are all on the same peg). <br />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: <br />Assume that the initial peg is on the left and the final peg is on the right. <br />Also assume quot; wrappingquot; - so the right peg counts as one peg quot; leftquot; of the left peg, and vice versa. <br />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 left, if n is odd, the disk located one peg to the right. <br />For example, in an 8-disk Hanoi:<br />Move 0 <br />The largest disk is 0, so it is on the left (initial) peg. <br />All other disks are 0 as well, so they are stacked on top of it. Hence all disks are on the initial peg. <br />Move 28-1 <br />The largest disk is 1, so it is on the right (final) peg. <br />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. <br />Move 0b11011000 = 21610 <br />The largest disk is 1, so it is on the right (final) peg. <br />Disk two is also 1, so it is stacked on top of it, on the right peg. <br />Disk three is 0, so it is on another peg. Since n is odd, it is one peg to the right, i.e. on the left peg. <br />Disk four is 1, so it is on another peg. Since n is still even, it is one peg to the left, i.e. on the right peg. <br />Disk five is also 1, so it is stacked on top of it, on the right peg. <br />Disk six is 0, so it is on another peg. Since n is even, the disk is one peg to the left, i.e. on the middle peg. <br />Disks seven and eight are also 0, so they are stacked on top of it, on the middle peg. <br />Graphical representation<br />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:<br />The graph for 2 disks is 3 triangles arranged in a larger triangle:<br />The nodes at the vertices of the outermost triangle represent distributions with all disks on the same peg.<br />For h+1 disks, take the graph of h disks and replace each small triangle with the graph for 2 disks.<br />For 3 disks the graph is:<br />call the pegs a, b and c <br />list disk positions from left to right in order of increasing size <br />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.<br />The game graph of level 7 shows the relatedness to the Sierpiński Triangle<br />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 the 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.<br />As more disks are added, the graph representation of the game will resemble the Fractal figure, 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.<br />The longest non-repetitive way for three disks can be visualized by erasing the unused edges:<br />The circular Hamiltonian path for three disks is:<br />The graphs clearly show that:<br />From every arbitrary distribution of disks, there is exactly one shortest way to move all disks onto one of the three pegs. <br />Between every pair of arbitrary distributions of disks there are one or two different shortest paths. <br />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. <br />Between every pair of arbitrary distributions of disks there are one or two different longest non selfcrossing paths. <br />Let Nh be the number of non selfcrossing paths for moving a tower of h disks from one peg to another one. Then: <br />N1=2 <br />Nh+1=(Nh)2+(Nh)3. <br />For example: N8≈1.5456x10795 <br />Applications<br />The Tower of Hanoi is frequently used in psychological research on problem solving. There also exists a variant of this task called Tower of London for neuropsychological diagnosis and treatment of executive functions.<br />The Tower of Hanoi is also used as Backup rotation scheme when performing computer data Backups where multiple tapes/media are involved.<br />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.<br />The Tower of Hanoi is also used as a test by neuropsychologists trying to evaluate frontal lobe deficits.<br /> <br />