Created
June 13, 2017 00:54
-
-
Save mhornbacher/19a8e7da4fddd5183bb173bbd63e907a to your computer and use it in GitHub Desktop.
Towers of Hanoi
This file contains hidden or 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
@counter = 0 | |
def move(n, source, target, spare) | |
print('.') if @counter % 1000000 == 0 # let the user know that we are working for each 1,000,000th call | |
if n > 0 | |
@counter += 1 | |
move(n - 1, source, spare, target) # move it to the spare so it is out of the way | |
target << source.pop() # in place memory manipulation, equivilent to pass by refrence. | |
move(n - 1, spare, target, source) # move the n - 1 disks that we left on spare onto target | |
else | |
return [source, target, spare] | |
end | |
end | |
def tower(levels) | |
start = *(1..levels) | |
move(levels, start, [], []) | |
end | |
def simple_eta_genreator(levels) | |
seconds = 2**levels - 1 | |
'%d days, %d hours, %d minutes, %d seconds' % | |
# the .reverse lets us put the larger units first for readability | |
[24,60,60].reverse.inject([seconds]) {|result, unitsize| | |
result[0,0] = result.shift.divmod(unitsize) | |
result | |
} | |
end | |
moves = 25 | |
puts("It would take you #{simple_eta_genreator(moves)} to do this. Give me some time...") | |
start = Time.now | |
res= tower(moves) #replace with height of tower | |
diff = Time.now - start | |
puts("\nMoves: #{@counter}\nResult#{res}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Algo taken from Wikipedia: https://en.wikipedia.org/wiki/Tower_of_Hanoi#Recursive_implementation