Last active
November 6, 2016 15:42
-
-
Save sanchojaf/71258d2b86e746c3049d386d14ad5496 to your computer and use it in GitHub Desktop.
Towers of Hanoi using Stack (stack, recursion)
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
# We have a pole with a certain number of disks staked on it; | |
# call this the source pole. We want move all of these to the | |
# destination pole, using a third (auxiliary) pole as an | |
# intermediate resting place. The catch is that you can move | |
# only one disk at the time, and you cannot ever place a larger | |
# disk onto a smaller one. | |
def towers(list) | |
while !list.empty? | |
n, src, dst, aux = list.pop | |
if n == 1 | |
puts "Move disk from #{src} to #{dst}" | |
else | |
list.push [n-1, aux, dst, src] | |
list.push [1, src, dst, aux] | |
list.push [n-1, src, aux, dst] | |
end | |
end | |
end | |
list = [] | |
list.push([3, "a", "c", "b"]) | |
towers(list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment