Created
January 13, 2014 23:15
-
-
Save 3den/8409977 to your computer and use it in GitHub Desktop.
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
class Tower | |
def initialize(name, rings) | |
@name = name | |
@rings = rings | |
end | |
def to_s | |
@name | |
end | |
def pop | |
@rings.pop | |
end | |
def push(ring) | |
@rings.push ring | |
end | |
def height | |
@rings.length | |
end | |
end | |
class Hanoi | |
def initialize(rings) | |
@left = Tower.new("left", [*(1..rings)].reverse) | |
@middle = Tower.new("middle", []) | |
@right = Tower.new("right", []) | |
end | |
def move(rings, from, to, other) | |
if rings == 1 | |
ring = from.pop | |
puts self | |
to.push ring | |
else | |
move(rings-1, from, other, to) | |
move(1, from, to, other) | |
move(rings-1, other, to, from) | |
end | |
end | |
def solve | |
move(@left.height, @left, @right, @middle) | |
end | |
def to_s | |
"#{@left.height} | #{@middle.height} | #{@right.height}" | |
end | |
end | |
h = Hanoi.new(ARGV[0].to_i) | |
h.solve | |
puts h |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment