-
Notifications
You must be signed in to change notification settings - Fork 7
/
solver.go
259 lines (209 loc) · 5.91 KB
/
solver.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main
import (
"github.com/gotk3/gotk3/gtk"
"time"
"fmt"
"log"
"math"
)
// this map contains a string representation of the
var visited = map[string]bool{}
var totalStates float64
var actualStates float64
// solves the puzzle
func Solver(puzzle *Puzzle) {
puzzle.WorkingGrid = createEmptyGrid(puzzle.OriginalGrid)
defer elapsed(*puzzle)()
visited = map[string]bool{}
solvePuzzle(puzzle, puzzle.Pieces)
if len(*puzzle.Solutions) > 0 {
puzzle.WorkingGrid = (*puzzle.Solutions)[0]
}
puzzle.IsRunning = false
if puzzle.HasGui {
puzzle.WinInfo.SolveButton.SetLabel("Find solutions")
}
}
// the recursive solving function
func solvePuzzle(puzzle *Puzzle, remainingPieces []Piece) {
if ! puzzle.IsRunning {
return
}
if puzzle.HasGui {
time.Sleep(time.Duration(puzzle.WinInfo.Speed) * time.Millisecond)
puzzle.WinInfo.MainWindow.QueueDraw()
}
if len(remainingPieces) == 0 {
addSolution(puzzle.Solutions, puzzle.WorkingGrid, puzzle.WinInfo.StatusBar, puzzle.HasGui)
return
}
minPieceSize := minPieceSize(remainingPieces)
// loops over the remaining pieces
for _, piece := range remainingPieces {
// considers all possible rotations of this piece
for _, rot := range piece.Rotations {
// tries every cell of the grid (limited to the positions where
// the piece is not outside the boundaries of the frame)
for j := 0; j <= len(puzzle.WorkingGrid[0])-len(rot[0]); j++ {
for i := 0; i <= len(puzzle.WorkingGrid)-len(rot); i++ {
actualStates ++
// if the cell is empty and the piece doesn't overlap with other pieces
if puzzle.WorkingGrid[i][j] == EMPTY && pieceFits(rot, i, j, puzzle.WorkingGrid) {
// adds the piece to the grid
updatedGrid := addShapeToGrid(rot, i, j, puzzle.WorkingGrid, piece.Number)
// checks for already visited states
if checkAndUpdateVisitedState(updatedGrid) {
continue
}
// if the piece doesn't leave any unfillable cell
if !hasLeftUnfillableAreas(updatedGrid, minPieceSize) {
// updates the remaining pieces
index, remainingPieces := removePieceFromRemaining(remainingPieces, piece)
// recursively calls this function
puzzle.WorkingGrid = updatedGrid
solvePuzzle(puzzle, remainingPieces)
// after having tried, remove this piece and goes on
updatedGrid = removeShapeFromGrid(updatedGrid, piece.Number)
puzzle.WorkingGrid = updatedGrid
remainingPieces = append(remainingPieces[:index], append([]Piece{piece}, remainingPieces[index:]...)...)
}
}
}
}
}
}
}
func checkAndUpdateVisitedState(grid Grid) bool {
gridString := fmt.Sprintf("%s", grid)
_, isPresent := visited[gridString]
if !isPresent {
visited[gridString] = true
}
return isPresent
}
func addSolution(solutions *[]Grid, solution Grid, statusBar gtk.Statusbar, useGui bool) []Grid {
for sol := range *solutions {
if areEqualPieces((*solutions)[sol], solution) {
return *solutions
}
}
*solutions = append(*solutions, solution)
if useGui {
statusBar.Push(1, fmt.Sprintf("Found %d solutions", len(*solutions)))
} else {
log.Printf("Solution #%d: %v", len(*solutions), solution)
}
return *solutions
}
func removePieceFromRemaining(pieces []Piece, piece Piece) (int, []Piece) {
for i, v := range pieces {
if v.Number == piece.Number {
return i, append(pieces[:i], pieces[i+1:]...)
}
}
log.Fatal("Trying to remove a not found piece from remaining ones.")
return -1, pieces
}
func hasLeftUnfillableAreas(grid Grid, minPieceSize int) bool {
var gridCopy = copyGrid(grid)
var min = math.MaxInt32
for i := 0; i < len(gridCopy); i++ {
for j := 0; j < len(gridCopy[0]); j++ {
if gridCopy[i][j] == EMPTY {
var area = getAreaSize(&gridCopy, i, j)
if min > area {
min = area
}
}
}
}
return min < minPieceSize
}
func getAreaSize(grid *Grid, x, y int) int {
(*grid)[x][y] = FLOOD_FILL_VALUE
size := 1
if y > 0 && (*grid)[x][y-1] == EMPTY {
size += getAreaSize(grid, x, y-1)
}
if x > 0 && (*grid)[x-1][y] == EMPTY {
size += getAreaSize(grid, x-1, y)
}
if x < len(*grid)-1 && (*grid)[x+1][y] == EMPTY {
size += getAreaSize(grid, x+1, y)
}
if y < len((*grid)[0])-1 && (*grid)[x][y+1] == EMPTY {
size += getAreaSize(grid, x, y+1)
}
return size
}
func pieceFits(shape Shape, dx, dy int, grid Grid) bool {
for i := 0; i < len(shape); i++ {
for j := 0; j < len(shape[0]); j++ {
if shape[i][j] != EMPTY && grid[i+dx][j+dy] != EMPTY {
return false
}
}
}
return true
}
func addShapeToGrid(shape Shape, dx, dy int, grid Grid, number uint8) Grid {
updatedGrid := copyGrid(grid)
for i := 0; i < len(shape); i++ {
for j := 0; j < len(shape[0]); j++ {
if shape[i][j] != EMPTY {
updatedGrid[dx+i][dy+j] = number
}
}
}
return updatedGrid
}
func removeShapeFromGrid(grid Grid, number uint8) Grid {
updatedGrid := copyGrid(grid)
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == number {
updatedGrid[i][j] = EMPTY
}
}
}
return updatedGrid
}
func elapsed(puzzle Puzzle) func() {
start := time.Now()
return func() {
message := fmt.Sprintf("Found %d solutions in %v.", len(*puzzle.Solutions), RoundedSince(start))
if puzzle.HasGui {
puzzle.WinInfo.StatusBar.Push(1, message)
} else {
log.Println(message)
}
}
}
func RoundedSince(value time.Time) time.Duration {
return time.Duration(time.Since(value)/time.Millisecond) * time.Millisecond
}
func createEmptyGrid(grid Grid) Grid {
var copiedGrid = make(Grid, len(grid))
for i := 0; i < len(grid); i++ {
copiedGrid[i] = make([]uint8, len(grid[0]))
}
return copiedGrid
}
func copyGrid(grid Grid) Grid {
copiedGrid := createEmptyGrid(grid)
var i, j int
for i = 0; i < len(grid); i++ {
for j = 0; j < len(grid[0]); j++ {
copiedGrid[i][j] = grid[i][j]
}
}
return copiedGrid
}
func Factorial(n uint64) uint64 {
var result uint64 = 1
var i uint64
for i=2; i<=n; i++ {
result *= i
}
return result
}