Skip to content

Instantly share code, notes, and snippets.

@supaspoida
Created Feb 2, 2013
Embed
What would you like to do?
brute force towers of hanoi
towers = [[nil,4,3,2,1],[nil],[nil]]
valid = [[nil],[nil],[nil,4,3,2,1]]
moves = []
record = ->(disc, from, to) {
names = { 0 => 'left ', 1 => 'center', 2 => 'right ' }
moves << "disc %s: %s -> %s" % [disc, names[from], names[to]]
}
move = ->(towers) {
return if towers == valid
disc = towers.select(&:last).sample.last
from_tower = towers.find { |t| t.last == disc }
from = towers.index(from_tower)
to_tower = towers.select { |t| t.last.nil? || t.last > disc }.sample
to = towers.index(to_tower)
if to
towers[to].push towers[from].pop
record[disc, from, to]
end
move[towers]
}
move[towers]
puts moves
puts "Finished in #{moves.count}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment