Created
April 23, 2016 15:41
-
-
Save omarismail/af8fcddff5f3623959bf595ec3c54dde to your computer and use it in GitHub Desktop.
Towers of Hanoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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