Skip to content

Instantly share code, notes, and snippets.

@mhornbacher
Created June 13, 2017 00:54
Show Gist options
  • Save mhornbacher/19a8e7da4fddd5183bb173bbd63e907a to your computer and use it in GitHub Desktop.
Save mhornbacher/19a8e7da4fddd5183bb173bbd63e907a to your computer and use it in GitHub Desktop.
Towers of Hanoi
@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}")
@mhornbacher
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment