Skip to content

Instantly share code, notes, and snippets.

@djo
Created January 22, 2014 13: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 djo/8559163 to your computer and use it in GitHub Desktop.
Save djo/8559163 to your computer and use it in GitHub Desktop.
The classic problem of the Towers of Hanoi.
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