File tree Expand file tree Collapse file tree 2 files changed +15
-1
lines changed Expand file tree Collapse file tree 2 files changed +15
-1
lines changed Original file line number Diff line number Diff line change @@ -32,6 +32,7 @@ func randomValue(choices uint16) uint8 {
32
32
func randomGrid () Grid {
33
33
for {
34
34
var s solver
35
+ s .init ()
35
36
// Fill cells with random values until the grid is complete
36
37
for _ , cell := range randomOrder () {
37
38
if s .grid [cell ] != 0 {
@@ -60,6 +61,7 @@ func minimize(g Grid) Grid {
60
61
g [cell ], value = uint8 (0 ), g [cell ]
61
62
var s solver
62
63
var grids []Grid
64
+ s .init ()
63
65
if ! s .load (& g ) {
64
66
panic ("minimize expects a valid grid" )
65
67
}
Original file line number Diff line number Diff line change @@ -32,12 +32,23 @@ type solver struct {
32
32
conflicts [81 ]uint16 // bitmask - uses bits 1 to 9 out of 16
33
33
}
34
34
35
+ func (s * solver ) init () {
36
+ // Allocate memory only once instead of growing the slice incrementally.
37
+ if s .next != nil {
38
+ panic ("must init only once" )
39
+ }
40
+ s .next = make ([]int , 0 , 81 )
41
+ }
42
+
35
43
func (s * solver ) copy () solver {
44
+ // Given that s.next is empty, sharing the same underlying array is fine.
45
+ // Indeed, mark() only pushes next steps in the queue and then pops them.
46
+ // Since search() explores options sequentially, reusing the same memory
47
+ // space for next steps doesn't cause problems.
36
48
if len (s .next ) > 0 {
37
49
panic ("must process next before making copy" )
38
50
}
39
51
copy := * s
40
- copy .next = nil // avoid sharing underlying array
41
52
return copy
42
53
}
43
54
@@ -141,6 +152,7 @@ func (s *solver) candidate() int {
141
152
func Solve (g * Grid ) []Grid {
142
153
var s solver
143
154
var grids []Grid
155
+ s .init ()
144
156
if s .load (g ) {
145
157
grids = s .search (grids )
146
158
}
You can’t perform that action at this time.
0 commit comments