Search⌘ K
AI Features

Solution: Tower of Hanoi

Explore solving the Tower of Hanoi using Ruby recursion and backtracking. This lesson guides you through the recursive base case, disk movements, and tracking steps, helping you master problem-solving with core Ruby programming techniques.

We'll cover the following...

Tower of Hanoi

Ruby 3.1.2
@move_logs = [] # save your move logs in this array
def solve_tower_hanoi(n, src_peg = "peg-A", spr_peg = "peg-B", des_peg = "peg-C")
if n > 0 # if there is a disk
solve_tower_hanoi(n-1, src_peg, des_peg, spr_peg)
@move_logs << "Moved disk-#{n} from #{src_peg} to #{des_peg}"
solve_tower_hanoi(n-1, spr_peg, src_peg, des_peg)
end
end

Explanation

  • Line 5: The base case is when the number of disks nn is 0.  

Note: For each recursive call, the second argument is the name of the source peg, the third argument is used as an intermediate peg and the last argument is the name of the destination peg. 

  • Line ...