lib/hanoi/jane/towers.rb in hanoi-jane-0.1.0 vs lib/hanoi/jane/towers.rb in hanoi-jane-0.1.1
- old
+ new
@@ -1,44 +1,74 @@
module Hanoi
module Jane
class Towers
- attr_reader :count, :stacks
+ include Enumerable
+ attr_reader :total, :stacks
+
def initialize discs
@discs = discs
- @count = 0
+ @total = 0
@base = 2
@stacks = [(0...discs).to_a.reverse, [], []]
end
def move
- @disc = Towers.diff Towers.rebase(@count, @base, @discs),
- Towers.rebase(@count += 1, @base, @discs)
- @source = find_disc
-
+ diff
+ find_disc
@stacks[find_stack].push @stacks[@source].pop
end
- def binary
- rebased
- end
-
- def rebased
- Towers.rebase @count, @base, @discs
- end
-
def solved
rebased.chars.all? { |digit| digit.to_i == @base - 1 }
end
def matrix
Matrix.new self
end
+ def inspect
+ {
+ stacks: @stacks,
+ moves: @total,
+ binary: rebased,
+ flipped: @disc
+ }
+ end
+
+ def each
+ yield self if @total == 0
+ until solved
+ move
+ yield self
+ end
+ end
+
+ def to_s
+ s = ''
+ @stacks.each do |stack|
+ s += stack.to_s
+ s += "\n"
+ end
+ s += '---'
+
+ s
+ end
+
+ def binary
+ rebased
+ end
+
+ def rebased
+ Towers.rebase @total, @base, @discs
+ end
+
+ private
+
def find_disc
@stacks.each_with_index do |stack, index|
- return index if stack.index @disc
+ @source = index if stack.index @disc
end
end
def find_stack #disc, source, stacks
# if the next stack is empty, move there
@@ -53,37 +83,22 @@
# default to the next one
return (@source + 1) % 3
end
- def inspect
- {
- stacks: @stacks,
- count: rebased
- }
- end
-
- def to_s
- s = ''
- @stacks.each do |stack|
- s += stack.to_s
- s += "\n"
+ def diff
+ this = binary
+ @total += 1
+ that = binary
+ this.chars.reverse.each_with_index do |bit, index|
+ if bit < that.chars.reverse[index]
+ @disc = index
+ end
end
- s += '---'
-
- s
end
def Towers.rebase value, base, width
'%0*d' % [width, value.to_s(base)]
- end
-
- def Towers.diff first, second
- first.chars.reverse.each_with_index do |bit, index|
- if bit < second.chars.reverse[index]
- return index
- end
- end
end
end
end
end