Visually shows the process of optimal solution of an hanoi tower problem. The function should not take more than O(n) time (n number of Moves. Start_y - peg_height * i, # Pegs are one on top of the other, height depends on iterationĭef visual_hanoi_simulation(number_of_pegs, base_width, peg_height, sleeping_interval): Todays question is to write a Non-recursive function to solve problem of Tower Of Hanoi. Start_x + (SPACE_PER_PEG - pegwidth)/2, # Handles alignment putting pegs in the middle, like a piramid The Wikipedia page on Tower of Hanoi has a section on a binary solution where the steps for an N-disk Tower of Hanoi are encoded in the binary representation of the numbers 0 to 2 N. (255-pegwidth, 255-pegwidth, 255-pegwidth), It can be programmed without recursion and without stacks (or simulated stacks). Alternate between moving the smallest disk and making the only valid move which does not involve the smallest disk. I'll just state the algorithm here.You may need to know the stack data structure in C to implement it There are three poles.The source pole,The auxiliary pole and The Destination pole. Tower of Hanoi - mechanical solution Arrange the three rods to form a triangle. Like in a piramid, the smaller in lighter color. Yes ,the Tower of Hanoi problem can be solved using iteration in C. Given a pile of pegs, displays them on the screen, nicely inpilated > for position in hanoi(,, ], 0, 2, 3): print positionĪssert len(pegs) >= n, 'not enough disks on peg'Īux = 3 - start - target # start + target + aux = 3įor i in hanoi(pegs, start, aux, n-1): yield iįor i in hanoi(pegs, start, target, 1): yield iįor i in hanoi(pegs, aux, target, n-1): yield iĭef display_pile_of_pegs(pegs, start_x, start_y, peg_height, screen): The sequence of optimal steps that leads to the solution. This function, given a starting position of an hanoi tower, yields The code is pretty simple, tested and documented, so no further introduction is needed. The logic of the solving is taken from StackOverflow (see links in docstring), I wrote the part dealing with the graphics, so review is most welcome on the graphical part that I wrote. I wrote a program to show graphically the solution of the problem of the Tower of Hanoi.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |