Created
January 22, 2014 13:58
-
-
Save djo/8559163 to your computer and use it in GitHub Desktop.
The classic problem of the 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
require 'minitest/autorun' | |
class Towers | |
class CantPlaceError < StandardError; end | |
attr_accessor :from, :to | |
def initialize(from, to) | |
@from = from | |
@to = to | |
@buffer = Array.new(from.size) | |
end | |
def move | |
move_disks(@from.size, @from, @to, @buffer) | |
end | |
private | |
def move_disks(n, from, to, buffer) | |
return if n <= 0 | |
move_disks(n - 1, from, buffer, to) | |
move_top(from, to) | |
move_disks(n - 1, buffer, to, from) | |
end | |
def move_top(from, to) | |
if to.any? && from.last > to.last | |
raise CantPlaceError.new("Can't place #{from.last} onto #{to.last}") | |
end | |
to.push(from.pop) | |
end | |
end | |
class TestTowers < MiniTest::Unit::TestCase | |
def test_move_disks | |
towers = Towers.new([3, 2, 1], []) | |
assert_equal towers.from, [3, 2, 1] | |
assert_equal towers.to, [] | |
towers.move | |
assert_equal towers.from, [] | |
assert_equal towers.to, [3, 2, 1] | |
end | |
def test_raise_cant_place | |
proc { | |
Towers.new([2, 3, 1], []).move | |
}.must_raise(Towers::CantPlaceError) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment