Skip to content

Instantly share code, notes, and snippets.

@supaspoida
Created February 2, 2013 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supaspoida/4695933 to your computer and use it in GitHub Desktop.
Save supaspoida/4695933 to your computer and use it in GitHub Desktop.
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