

It is associated with a legend of a Hindu temple where the puzzle was supposedly used to increase the mental discipline of young priests. The tower of Hanoi (also called the tower of Brahma or the Lucas tower) was invented by a French mathematician Édouard Lucas in the 19th century. But math can also be used for entertainment-mathematical games, riddles, challenges and puzzles are also interwoven throughout history! Throughout history mathematics has fulfilled many practical needs such as measuring plots of land, studying astronomy and calculating taxes. People have been playing these games and puzzles for centuries! They are fun, entertaining and sometimes useful. Think about simple games such as tic-tac-toe, more strategic games such as chess or math puzzles such as sudoku. Maybe you noticed our hanoi function did not mutated objects because it calls itself with new arguments rather than using existing objects.Are you tired of math work sheets and homework? Did you know that there are more creative ways to exercise your mathematical muscle? A lot of games, puzzles and riddles revolve around mathematical concepts. 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 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
