Skip to content

Commit 7ad5848

Browse files
committed
Optimize by removing all memory allocations.
1 parent 5180238 commit 7ad5848

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

go/sudoku/solver.go

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -40,18 +40,6 @@ func (s *solver) init() {
4040
s.next = make([]int, 0, 81)
4141
}
4242

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.
48-
if len(s.next) > 0 {
49-
panic("must process next before making copy")
50-
}
51-
copy := *s
52-
return copy
53-
}
54-
5543
func (s *solver) load(grid *Grid) bool {
5644
for cell, value := range grid {
5745
if value == 0 {
@@ -119,11 +107,20 @@ func (s *solver) search(grids []Grid) []Grid {
119107
return grids
120108
}
121109

110+
// Since s.next is empty, sharing the underlying array with a copy is OK.
111+
// Indeed, mark() only pushes next steps in the queue and then pops them.
112+
// Since search() explores options sequentially, reusing the same memory
113+
// space for next steps doesn't cause problems.
114+
if len(s.next) > 0 {
115+
panic("must process next before searching")
116+
}
117+
122118
// Try all possible values of the cell with the fewest choices.
119+
var copy solver
123120
cell := s.candidate()
124121
for value := uint8(1); value < uint8(10); value++ {
125122
if s.conflicts[cell]&(1<<value) == 0 {
126-
copy := s.copy()
123+
copy = *s
127124
if copy.mark(cell, value) {
128125
grids = copy.search(grids)
129126
}

0 commit comments

Comments
 (0)