-
Notifications
You must be signed in to change notification settings - Fork 2
/
solution.go
199 lines (165 loc) · 4.72 KB
/
solution.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package watersort
import (
"container/heap"
"errors"
"fmt"
"log"
"math/rand"
)
type solution struct {
State State
Steps []Step
Score int
}
// Clone returns a deep copy of s.
func (s solution) Clone() solution {
state := s.State.Clone()
steps := make([]Step, len(s.Steps))
copy(steps, s.Steps)
return solution{
State: state,
Steps: steps,
Score: s.Score,
}
}
// PossibleSteps returns all available next steps.
// If there are no possible moves (meaning the game is lost) it returns nil.
//
// First, the function creates a map of colors to possible destinations
// (i.e. bottles that are not full and where c is the top color, and empty bottles).
//
// Then it iterates over each bottle, determines its top color, and finds
// possible destination for this color using the precomputed map.
//
// Precomputing possible destinations per color reduces the bottle selection complexity from O(n²) to O(n)
// (where n is the number of bottles/colors), assuming that Bottle.TopColor() is O(1).
// (Bottle.TopColor() needs to skip empty spaces, of which there are (usually) 2× m, where m is the bottle size.
// Assuming a linear relationship between n and m, armortized runtime of Bottle.TopColor() is constant.
// Usually n > m.)
func (s solution) PossibleSteps() []Step {
destinationsByColor := make(map[Color][]int)
for i, b := range s.State.Bottles {
if b.FreeSlots() == 0 {
continue
}
tc := b.TopColor()
destinationsByColor[tc] = append(destinationsByColor[tc], i)
}
var ret []Step
for srcIndex, src := range s.State.Bottles {
tc := src.TopColor()
if tc == Empty {
continue
}
for _, dstIndex := range append(destinationsByColor[tc], destinationsByColor[Empty]...) {
if srcIndex == dstIndex {
continue
}
ret = append(ret, Step{
From: srcIndex,
To: dstIndex,
Color: tc,
})
}
}
rand.Shuffle(len(ret), func(i, j int) {
ret[i], ret[j] = ret[j], ret[i]
})
return ret
}
// Step represents one state change, i.e. the pouring from bottle "From" to bottle "To".
type Step struct {
From, To int
Color
}
func (s Step) String() string {
return fmt.Sprintf("pour %2d onto %2d (%v)", s.From+1, s.To+1, s.Color)
}
type minHeap struct {
Solutions []solution
}
func (h minHeap) Len() int {
return len(h.Solutions)
}
func (h minHeap) Less(i, j int) bool {
a, b := h.Solutions[i], h.Solutions[j]
if a.Score != b.Score {
return a.Score < b.Score
}
// Tie breaker: sort solutions with many steps in front of solutions with fewer steps.
// This leads to the algorithm "greedily" trying longer solutions first,
// before back-tracking to shorter solutions.
return len(a.Steps) > len(b.Steps)
}
func (h *minHeap) Swap(i, j int) {
h.Solutions[i], h.Solutions[j] = h.Solutions[j], h.Solutions[i]
}
func (h *minHeap) Push(x any) {
h.Solutions = append(h.Solutions, x.(solution))
}
func (h *minHeap) Pop() any {
last := h.Len() - 1
s := h.Solutions[last]
h.Solutions = h.Solutions[:last]
return s
}
var ErrNoSolution = errors.New("there is no solution")
type Option func(*option)
type option struct {
reportComplexity *int
}
func ReportComplexity(out *int) Option {
return func(opt *option) {
opt.reportComplexity = out
}
}
// Solve calculates an optimal solution for s using an A* search algorithm.
//
// The score of each (partial) solution is calculated as the sum of the number
// of steps so far (len(Solution.Steps)) and Solution.State.MinRequiredMoves().
//
// If s is unsolvable, an error is returned.
// Use `errors.Is(ErrNoSolution)` to distinguish between this and other errors.
func (s State) Solve(opts ...Option) ([]Step, error) {
sol := solution{
State: s,
}
var opt option
for _, f := range opts {
f(&opt)
}
// h holds partial solutions.
// Pop() returns (one of) the solution closest to a solved state.
h := &minHeap{}
heap.Init(h)
heap.Push(h, sol)
// seen holds the CRC32 checksum of previously seen states to avoid cycles.
seen := make(map[uint32]bool)
for len(h.Solutions) > 0 {
base := heap.Pop(h).(solution)
for _, step := range base.PossibleSteps() {
next := base.Clone()
if err := next.State.Apply(step); err != nil {
log.Printf("State.Apply(%v): %v", step, err)
continue
}
chk := next.State.checksum()
if seen[chk] {
continue
}
next.Steps = append(next.Steps, step)
minRequiredMoves := next.State.minRequiredMoves()
next.Score = len(next.Steps) + minRequiredMoves
// log.Printf("Distance: %2d + %2d = %2d", len(next.Steps), minRequiredMoves, next.Distance)
if minRequiredMoves == 0 {
if opt.reportComplexity != nil {
*opt.reportComplexity = len(seen)
}
return next.Steps, nil
}
seen[chk] = true
heap.Push(h, next)
}
}
return nil, fmt.Errorf("evaluated %d states: %w", len(seen), ErrNoSolution)
}