![]() ![]() ![]() Maybe you noticed our hanoi function did not mutated objects because it calls itself with new arguments rather than using existing objects. It is important to understand that a recursive function needs a mechanism to stop executing, otherwise it will run forever or in the worst case it will cause errors. I do not want you to understand the math behind the Hanoi Tower algorithm, just want you to realize that calling function hanoi in the same function hanoi is recursion. ![]() Notice, the arguments are the same but in different order, again allowing us to solve the puzzle. Hanoi(number - 1, auxiliar, origin, destination) Puts "Moved disc from #"įinally, we will call hanoi again because we want to move the disks. Third, we also want to print whenever the disks are moving from one place to another. Hanoi(number - 1, origin, destination, auxiliar)īasically, we are calling the same function ( hanoi) but using new arguments, allowing us to solve the puzzle. Second, we will have to decrement the amount of disks when calling hanoi and pass along the origin, destination and auxiliar. Our next mission is to actually figure out the puzzle (moving all the disks from "A" to "C"). Our program continues executing unless the disks is equal to zero. It must stop when all the disks has been moved to the column C. The first move is produced by the first recursive call in the code, which is repeatedly invoked many times, until the base case is reached - printing the first move. the objective is to move them to tower 2, making also use of an auxiliary tower 3. The idea is to write a function that calls itself until the puzzle is solved.įirst, determine when to stop the function execution. To make this example easier to understand, let's pretend our Hanoi Tower has 4 disks, and columns A, B, C. Enter fullscreen mode Exit fullscreen mode ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |