Skip to content

Instantly share code, notes, and snippets.

@semmin
Last active August 29, 2015 14:06
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 semmin/06121ae0b7c52dec73e5 to your computer and use it in GitHub Desktop.
Save semmin/06121ae0b7c52dec73e5 to your computer and use it in GitHub Desktop.
Towers of Hanoi in Ruby with tests
class Peg
attr_accessor :title, :rings
def initialize(title: , rings: 0)
@title = title
@rings = Array(1..rings)
end
end
def move(rings, from, destination, other)
if rings == 1
ring = from.rings.pop
p "Move ring #{ring} from #{from.title} to #{destination.title}"
destination.rings.push ring
else
move(rings-1, from, other, destination)
move(1, from, destination, other)
move(rings-1, other, destination, from)
end
end
def towers_of_hanoi()
p "Please enter the number of disks (#1 will be the biggest): "
number_of_rings = gets().to_i
from = Peg.new(title: :From, rings: number_of_rings)
to = Peg.new(title: :To, rings: 0)
via = Peg.new(title: :Via, rings: 0)
move number_of_rings, from, to, via
end
towers_of_hanoi
require "test/unit"
class TestTowersOfHanoi < Test::Unit::TestCase
def setup
@peg = Peg.new(title: "A", rings: 3)
end
def test_peg_title
assert_equal("A",@peg.title)
end
def test_peg_rings
assert_equal(Array, @peg.rings.class)
assert_equal(3, @peg.rings.size)
end
def test_moves_rings
from = Peg.new(title: :From, rings: 5)
to = Peg.new(title: :To, rings: 0)
via = Peg.new(title: :Via, rings: 0)
move 5, from, to, via
assert_equal 0, from.rings.size
assert_equal 0, via.rings.size
assert_equal 5, to.rings.size
end
def test_runs_with_no_exceptions
from = Peg.new(title: :From, rings: 5)
to = Peg.new(title: :To, rings: 0)
via = Peg.new(title: :Via, rings: 0)
assert_nothing_raised do
move 5, from, to, via
end
end
def teardown
@peg = nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment