Solution: Tower of Hanoi

Go over the recursive solution for the Tower of Hanoi problem.

We'll cover the following...

Tower of Hanoi

Press + to interact
@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 ...