Created
February 2, 2013 02:58
-
-
Save supaspoida/4695933 to your computer and use it in GitHub Desktop.
brute force 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
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