Skip to content

Instantly share code, notes, and snippets.

@omarismail
Created April 23, 2016 15:41
Show Gist options
  • Save omarismail/af8fcddff5f3623959bf595ec3c54dde to your computer and use it in GitHub Desktop.
Save omarismail/af8fcddff5f3623959bf595ec3c54dde to your computer and use it in GitHub Desktop.
Towers of Hanoi
def move(num_disks, start, mid, last)
if num_disks == 1
@towers[last] << @towers[start].pop
puts "Move disks from #{start} to #{last} : #{@towers}"
else
move(num_disks-1, start, last, mid)
move(1, start, mid, last)
move(num_disks-1, mid, start, last)
end
end
n = 5
start = 0
mid = 1
last = 2
@towers = [[*1..n].reverse, [], []]
move(n, start, mid, last)
# Move disks from 0 to 2 : [[5, 4, 3, 2], [], [1]]
# Move disks from 0 to 1 : [[5, 4, 3], [2], [1]]
# Move disks from 2 to 1 : [[5, 4, 3], [2, 1], []]
# Move disks from 0 to 2 : [[5, 4], [2, 1], [3]]
# Move disks from 1 to 0 : [[5, 4, 1], [2], [3]]
# Move disks from 1 to 2 : [[5, 4, 1], [], [3, 2]]
# Move disks from 0 to 2 : [[5, 4], [], [3, 2, 1]]
# Move disks from 0 to 1 : [[5], [4], [3, 2, 1]]
# Move disks from 2 to 1 : [[5], [4, 1], [3, 2]]
# Move disks from 2 to 0 : [[5, 2], [4, 1], [3]]
# Move disks from 1 to 0 : [[5, 2, 1], [4], [3]]
# Move disks from 2 to 1 : [[5, 2, 1], [4, 3], []]
# Move disks from 0 to 2 : [[5, 2], [4, 3], [1]]
# Move disks from 0 to 1 : [[5], [4, 3, 2], [1]]
# Move disks from 2 to 1 : [[5], [4, 3, 2, 1], []]
# Move disks from 0 to 2 : [[], [4, 3, 2, 1], [5]]
# Move disks from 1 to 0 : [[1], [4, 3, 2], [5]]
# Move disks from 1 to 2 : [[1], [4, 3], [5, 2]]
# Move disks from 0 to 2 : [[], [4, 3], [5, 2, 1]]
# Move disks from 1 to 0 : [[3], [4], [5, 2, 1]]
# Move disks from 2 to 1 : [[3], [4, 1], [5, 2]]
# Move disks from 2 to 0 : [[3, 2], [4, 1], [5]]
# Move disks from 1 to 0 : [[3, 2, 1], [4], [5]]
# Move disks from 1 to 2 : [[3, 2, 1], [], [5, 4]]
# Move disks from 0 to 2 : [[3, 2], [], [5, 4, 1]]
# Move disks from 0 to 1 : [[3], [2], [5, 4, 1]]
# Move disks from 2 to 1 : [[3], [2, 1], [5, 4]]
# Move disks from 0 to 2 : [[], [2, 1], [5, 4, 3]]
# Move disks from 1 to 0 : [[1], [2], [5, 4, 3]]
# Move disks from 1 to 2 : [[1], [], [5, 4, 3, 2]]
# Move disks from 0 to 2 : [[], [], [5, 4, 3, 2, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment