Rosetta Code
Towers of Hanoi
Solve Towers of Hanoi recursively and return the ordered move list for a small deterministic puzzle.
Source
rosettacode/popular/towers_of_hanoi.vibe
# title: Towers of Hanoi
# source: https://rosettacode.org/wiki/Towers_of_Hanoi
# category: Rosetta Code
# difficulty: Medium
# summary: Solve Towers of Hanoi recursively and return the ordered move list for a small deterministic puzzle.
# tags: popular, recursion, classic-cs, puzzles
# vibe: 0.2
def hanoi_moves(disks, from_peg, to_peg, spare_peg)
if disks == 0
[]
else
hanoi_moves(disks - 1, from_peg, spare_peg, to_peg) + [{ disk: disks, from: from_peg, to: to_peg }] + hanoi_moves(disks - 1, spare_peg, to_peg, from_peg)
end
end
def run
moves = hanoi_moves(3, 1, 3, 2)
{
move_count: moves.size,
moves: moves
}
end
Output
Press run to execute run from this example.