-
Notifications
You must be signed in to change notification settings - Fork 0
/
constrained_towers.rb
64 lines (55 loc) · 1.16 KB
/
constrained_towers.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class ConstrainedTowers < Towers
def initialize discs
super
@ternary = ConstrainedTowers.ternarise @count, @discs
@directions = {}
@stacks[0].each do |disc|
@directions[disc] = :right
end
end
def move
@flip = Towers.diff ConstrainedTowers.ternarise(@count, @discs),
ConstrainedTowers.ternarise(@count += 1, @discs)
@source = find_disc
@stacks[find_stack].push @stacks[@source].pop
end
def find_disc
@stacks.each_with_index do |stack, index|
return index if stack.index @flip
end
end
def find_stack
case @source
when 0
@directions[@flip] = :right
return 1
when 2
@directions[@flip] = :left
return 1
when 1
if @directions[@flip] == :right
return 2
else
return 0
end
end
end
def binary
ternary
end
def ternary
ConstrainedTowers.ternarise @count, @discs
end
def solved
ternary.chars.all? { |trit| trit.to_i == 2 }
end
def inspect
{
stacks: @stacks,
count: ternary
}
end
def ConstrainedTowers.ternarise value, width
'%0*d' % [width, value.to_s(3)]
end
end