-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku.go
651 lines (578 loc) · 15.8 KB
/
sudoku.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
package sudoku
import (
"bytes"
"fmt"
"github.com/wcharczuk/go-chart/v2"
"io/ioutil"
"log"
"math/rand"
"os"
"strconv"
"strings"
"sync"
"time"
)
var logger = log.New(os.Stdout, "", 0)
type Grid [][]int
//isSolved tells if this sudoku has been solved or not
//works for both 9x9 sudokus and 21*21 samurai sudokus
func (g Grid) isSolved() bool {
for _, row := range g {
for _, num := range row {
if num == 0 {
return false
}
}
}
return true
}
// Move A single move in sudoku
type Move struct {
thread int
position Position // Position of the sudoku this Move was done in
row int
column int
num int // Number inserted
time time.Time
}
func (m Move) String() string {
buf := bytes.Buffer{}
fmt.Fprintf(&buf, "%d,%d,%s,%d,%d,%d", m.time.UnixMicro(), m.thread, m.position, m.row, m.column, m.num)
return buf.String()
}
type Tracker struct {
moves []Move
startTime time.Time
}
func (t *Tracker) resetMoves() {
t.moves = nil
t.startTime = time.Now()
}
//SamuraiGridFromFile reads a samurai sudoku grid from a given file
func SamuraiGridFromFile(filePath string) Grid {
const samuraiLength = 21
grid := make(Grid, samuraiLength)
buffer, err := ioutil.ReadFile(filePath)
if err != nil {
logger.Printf("File couldn't be read!")
}
sudokuContents := string(buffer)
for j, line := range strings.Split(sudokuContents, "\n") {
charRow := strings.Split(line, "")
intRow := make([]int, samuraiLength, samuraiLength)
offset := 0
for i := 0; i < samuraiLength; i++ {
switch len(charRow) {
case 9:
if i < 6 || 15 <= i {
intRow[i] = -1
offset++
} else {
num, _ := strconv.Atoi(charRow[i-offset])
intRow[i] = num
}
case 18:
if 9 <= i && i < 12 {
intRow[i] = -1
offset++
} else {
num, _ := strconv.Atoi(charRow[i-offset])
intRow[i] = num
}
default:
num, _ := strconv.Atoi(charRow[i-offset])
intRow[i] = num
}
}
grid[j] = intRow
}
logger.Printf("Read \n%v\n", grid)
return grid
}
type SamuraiSudoku struct {
mu sync.Mutex
grid Grid
initialGrid Grid
tracker Tracker
}
func (s *SamuraiSudoku) ResetGrid() {
s.tracker.resetMoves()
for i, row := range s.initialGrid {
for j, num := range row {
s.grid[i][j] = num
}
}
}
func (s *SamuraiSudoku) Grid() Grid {
return s.grid
}
func (s *SamuraiSudoku) SetGrid(grid Grid) {
if s.initialGrid == nil {
s.initialGrid = make(Grid, len(grid))
for i := range grid {
s.initialGrid[i] = make([]int, len(grid[i]))
copy(s.initialGrid[i], grid[i])
}
}
s.grid = grid
}
type Position int
const (
TopLeft Position = iota + 1
TopRight
Centre
BottomLeft
BottomRight
)
type ThreadId int
const (
Thread1 ThreadId = iota + 1
Thread2
)
func (p Position) String() string {
switch p {
case TopLeft:
return "top left"
case TopRight:
return "top right"
case Centre:
return "centre"
case BottomLeft:
return "bottom left"
case BottomRight:
return "bottom right"
}
return "unknown"
}
func (g Grid) String() string {
var buf bytes.Buffer
var char string
for _, row := range g {
for _, num := range row {
if num == -1 {
char = " "
} else {
char = strconv.Itoa(num)
}
_, err := fmt.Fprint(&buf, char, " ")
if err != nil {
return ""
}
}
_, err := fmt.Fprint(&buf, "\n")
if err != nil {
return ""
}
}
return buf.String()
}
//GetSubSudoku returns sub-sudoku for given position, assuming 21*21 samurai sudoku grid
func (s *SamuraiSudoku) GetSubSudoku(position Position) Grid {
var grid = s.grid
subSudoku := make(Grid, 9)
var tmp Grid
switch position {
case TopLeft:
tmp = grid[0:9]
for i := range tmp {
subSudoku[i] = tmp[i][0:9]
}
case TopRight:
tmp = grid[0:9]
for i := range tmp {
subSudoku[i] = tmp[i][12:21]
}
case Centre:
tmp = grid[6:15]
for i := range tmp {
subSudoku[i] = tmp[i][6:15]
}
case BottomLeft:
tmp = grid[12:21]
for i := range tmp {
subSudoku[i] = tmp[i][0:9]
}
case BottomRight:
tmp = grid[12:21]
for i := range tmp {
subSudoku[i] = tmp[i][12:21]
}
}
return subSudoku
}
func (s *SamuraiSudoku) recordMove(id ThreadId, position Position, y int, x int, n int) {
s.tracker.moves = append(s.tracker.moves, Move{
thread: int(position)*10 + int(id),
position: position,
row: y,
column: x,
num: n,
time: time.Now().Add(time.Now().Sub(s.tracker.startTime)),
})
}
func (s *SamuraiSudoku) moves() bytes.Buffer {
buf := bytes.Buffer{}
fmt.Fprintf(&buf, "time (microseconds),thread id, position, row, colmun, value\n")
for _, move := range s.tracker.moves {
fmt.Fprintf(&buf, "%s\n", move.String())
}
return buf
}
//SolveSamuraiSudoku solves 21*21 samurai sudoku
func SolveSamuraiSudoku(samurai *SamuraiSudoku) Grid {
// get all subsudokus
subSudokus := []struct {
position Position
sudoku Grid
}{
{TopLeft, samurai.GetSubSudoku(TopLeft)},
{TopRight, samurai.GetSubSudoku(TopRight)},
{Centre, samurai.GetSubSudoku(Centre)},
{BottomLeft, samurai.GetSubSudoku(BottomLeft)},
{BottomRight, samurai.GetSubSudoku(BottomRight)},
}
// iterate over the map until all subsudokus are solved
for _, subSudoku := range subSudokus {
SolveSudoku(subSudoku.sudoku, subSudoku.position, samurai)
}
return samurai.Grid()
}
//ConcurrentSolveSamuraiSudoku solves 21*21 samurai sudoku concurrently
func ConcurrentSolveSamuraiSudoku(samurai *SamuraiSudoku) Grid {
rand.Seed(time.Now().UnixNano())
// get all subsudokus
getSubSudokus := func() []struct {
position Position
sudoku Grid
} {
subSudokus := []struct {
position Position
sudoku Grid
}{
{TopLeft, samurai.GetSubSudoku(TopLeft)},
{TopRight, samurai.GetSubSudoku(TopRight)},
{Centre, samurai.GetSubSudoku(Centre)},
{BottomLeft, samurai.GetSubSudoku(BottomLeft)},
{BottomRight, samurai.GetSubSudoku(BottomRight)},
}
rand.Shuffle(len(subSudokus), func(i, j int) {
subSudokus[i], subSudokus[j] = subSudokus[j], subSudokus[i]
})
return subSudokus
}
wg := new(sync.WaitGroup)
// iterate over the map until all subsudokus are solved
for !samurai.Grid().isSolved() {
samurai.mu.Lock()
samurai.ResetGrid()
subSudokus := getSubSudokus()
// reset samurai grid
samurai.mu.Unlock()
solvingLoop(samurai, subSudokus, wg)
SolvingAttempts++
}
moves := samurai.moves()
os.WriteFile("sudoku.log", moves.Bytes(), 0666)
logger.Printf("attempt %d\n%v\n", SolvingAttempts, samurai.Grid())
return samurai.Grid()
}
//DoubleThreadSolveSamuraiSudoku solves 21*21 samurai sudoku concurrently
func DoubleThreadSolveSamuraiSudoku(samurai *SamuraiSudoku) Grid {
rand.Seed(time.Now().UnixNano())
// get all subsudokus
getSubSudokus := func() []struct {
position Position
sudoku Grid
} {
subSudokus := []struct {
position Position
sudoku Grid
}{
{TopLeft, samurai.GetSubSudoku(TopLeft)},
{TopRight, samurai.GetSubSudoku(TopRight)},
{Centre, samurai.GetSubSudoku(Centre)},
{BottomLeft, samurai.GetSubSudoku(BottomLeft)},
{BottomRight, samurai.GetSubSudoku(BottomRight)},
}
rand.Shuffle(len(subSudokus), func(i, j int) {
subSudokus[i], subSudokus[j] = subSudokus[j], subSudokus[i]
})
return subSudokus
}
wg := new(sync.WaitGroup)
// iterate over the map until all subsudokus are solved
for !samurai.Grid().isSolved() {
samurai.mu.Lock()
samurai.ResetGrid()
subSudokus := getSubSudokus()
// reset samurai grid
samurai.mu.Unlock()
doubleSolvingLoop(samurai, subSudokus, wg)
SolvingAttempts++
}
moves := samurai.moves()
os.WriteFile("sudoku.csv", moves.Bytes(), 0666)
logger.Printf("attempt %d\n%v\n", SolvingAttempts, samurai.Grid())
return samurai.Grid()
}
var SolvingAttempts = 0
func solvingLoop(samurai *SamuraiSudoku, subSudokus []struct {
position Position
sudoku Grid
}, wg *sync.WaitGroup) {
wg.Add(len(subSudokus))
for _, subSudoku := range subSudokus {
// increment WaitGroup counter
go concurrentSolveSudoku(Thread1, subSudoku.sudoku, subSudoku.position, samurai, wg)
}
wg.Wait()
var order bytes.Buffer
// populate order buffer for debugging purposes
for _, sudokus := range subSudokus {
_, err := fmt.Fprintf(&order, "%d, ", sudokus.position)
if err != nil {
return
}
}
}
func doubleSolvingLoop(samurai *SamuraiSudoku, subSudokus []struct {
position Position
sudoku Grid
}, wg *sync.WaitGroup) {
wg.Add(len(subSudokus) * 2)
for _, subSudoku := range subSudokus {
// increment WaitGroup counter
go concurrentSolveSudoku(Thread2, subSudoku.sudoku, subSudoku.position, samurai, wg)
go concurrentSolveSudoku(Thread1, subSudoku.sudoku, subSudoku.position, samurai, wg)
}
wg.Wait()
var order bytes.Buffer
// populate order buffer for debugging purposes
for _, sudokus := range subSudokus {
_, err := fmt.Fprintf(&order, "%d, ", sudokus.position)
if err != nil {
return
}
}
}
//possible checks if index y,x in grid position can be filled with n in all subsudokus it's in
func possible(sudoku Grid, y int, x int, n int, position Position, samuraiSudoku *SamuraiSudoku) bool {
var sharedSudoku Grid
var yShared, xShared int
switch position {
case TopLeft:
if 6 <= y && y < 9 && 6 <= x && x < 9 {
sharedSudoku = samuraiSudoku.GetSubSudoku(Centre)
yShared, xShared = y-6, x-6
}
case TopRight:
if 6 <= y && y < 9 && 0 <= x && x < 3 {
sharedSudoku = samuraiSudoku.GetSubSudoku(Centre)
yShared, xShared = y-6, x+6
}
case Centre:
if 0 <= y && y < 3 && 0 <= x && x < 3 {
sharedSudoku = samuraiSudoku.GetSubSudoku(TopLeft)
yShared, xShared = y+6, x+6
} else if 0 <= y && y < 3 && 6 <= x && x < 9 {
sharedSudoku = samuraiSudoku.GetSubSudoku(TopRight)
yShared, xShared = y+6, x-6
} else if 6 <= y && y < 9 && 0 <= x && x < 3 {
sharedSudoku = samuraiSudoku.GetSubSudoku(BottomLeft)
yShared, xShared = y-6, x+6
} else if 6 <= y && y < 9 && 6 <= x && x < 9 {
sharedSudoku = samuraiSudoku.GetSubSudoku(BottomRight)
yShared, xShared = y-6, x-6
}
case BottomLeft:
if 0 <= y && y < 3 && 6 <= x && x < 9 {
sharedSudoku = samuraiSudoku.GetSubSudoku(Centre)
yShared, xShared = y+6, x-6
}
case BottomRight:
if 0 <= y && y < 3 && 0 <= x && x < 3 {
sharedSudoku = samuraiSudoku.GetSubSudoku(Centre)
yShared, xShared = y+6, x+6
}
}
if len(sharedSudoku) == 0 {
return possibleSudoku(sudoku, y, x, n)
} else {
return possibleSudoku(sudoku, y, x, n) && possibleSudoku(sharedSudoku, yShared, xShared, n)
}
}
//possibleSudoku checks if sudoku can be filled in position y,x with n
func possibleSudoku(sudoku Grid, y int, x int, n int) bool {
for i := 0; i < 9; i++ {
if sudoku[y][i] == n {
return false
}
}
for i := 0; i < 9; i++ {
if sudoku[i][x] == n {
return false
}
}
x0 := (x / 3) * 3
y0 := (y / 3) * 3
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if sudoku[y0+i][x0+j] == n {
return false
}
}
}
return true
}
//concurrentSolveSudoku solves 9x9 subsudoku in specified position within samuraiSudoku, concurrently
func concurrentSolveSudoku(threadId ThreadId, sudoku Grid, position Position, samuraiSudoku *SamuraiSudoku, wg *sync.WaitGroup) Grid {
// TODO: fix some sudokus not solving.
if sudoku.isSolved() {
wg.Done()
return sudoku
}
if threadId == Thread1 {
reverseBacktrack(threadId, sudoku, position, samuraiSudoku)
} else {
backtrack(threadId, sudoku, position, samuraiSudoku)
}
wg.Done()
return sudoku
}
//SolveSudoku solves 9x9 subsudoku in position within samuraiSudoku
func SolveSudoku(sudoku Grid, position Position, samuraiSudoku *SamuraiSudoku) Grid {
backtrack(Thread1, sudoku, position, samuraiSudoku)
return sudoku
}
//backtrack keeps attempting values recursively until 9x9 sudoku is solved completely
func backtrack(threadId ThreadId, sudoku Grid, position Position, samuraiSudoku *SamuraiSudoku) bool {
for y := 0; y < 9; y++ {
for x := 0; x < 9; x++ {
// if cell is empty
//logger.Printf("%s: waiting for lock...", position)
samuraiSudoku.mu.Lock()
//logger.Printf("%s: locked", position)
if sudoku[y][x] == 0 {
for n := 1; n < 10; n++ {
if possible(sudoku, y, x, n, position, samuraiSudoku) {
samuraiSudoku.recordMove(threadId, position, y, x, n)
sudoku[y][x] = n
samuraiSudoku.mu.Unlock()
//logger.Printf("%s: set sudoku[%d, %d] = %d", position, y, x, n)
if backtrack(threadId, sudoku, position, samuraiSudoku) {
// should be unlocked here, but could get locked by other threads
return true
}
//logger.Printf("%s: waiting for lock for 0", position)
samuraiSudoku.mu.Lock()
//logger.Printf("%s: acquired lock for 0", position)
samuraiSudoku.recordMove(threadId, position, y, x, 0)
sudoku[y][x] = 0
//logger.Printf("%s: releasing lock after 0", position)
//samuraiSudoku.mu.Unlock()
}
}
//logger.Printf("%s: returning false, %d %d", position, y, x)
samuraiSudoku.mu.Unlock()
return false
}
//logger.Printf("%s: released lock, %d, %d", position, y, x)
samuraiSudoku.mu.Unlock()
}
}
//samuraiSudoku.mu.Unlock()
return true
}
//reverseBacktrack keeps attempting values recursively until 9x9 sudoku is solved completely from the bottom
func reverseBacktrack(threadId ThreadId, sudoku Grid, position Position, samuraiSudoku *SamuraiSudoku) bool {
for y := 8; y >= 0; y-- {
for x := 8; x >= 0; x-- {
// if cell is empty
//logger.Printf("%s: waiting for lock...", position)
samuraiSudoku.mu.Lock()
//logger.Printf("%s: locked", position)
if sudoku[y][x] == 0 {
for n := 1; n < 10; n++ {
if possible(sudoku, y, x, n, position, samuraiSudoku) {
samuraiSudoku.recordMove(threadId, position, y, x, n)
sudoku[y][x] = n
samuraiSudoku.mu.Unlock()
//logger.Printf("%s: set sudoku[%d, %d] = %d", position, y, x, n)
if reverseBacktrack(threadId, sudoku, position, samuraiSudoku) {
// should be unlocked here, but could get locked by other threads
return true
}
//logger.Printf("%s: waiting for lock for 0", position)
samuraiSudoku.mu.Lock()
//logger.Printf("%s: acquired lock for 0", position)
samuraiSudoku.recordMove(threadId, position, y, x, 0)
sudoku[y][x] = 0
//logger.Printf("%s: releasing lock after 0", position)
//samuraiSudoku.mu.Unlock()
}
}
//logger.Printf("%s: returning false, %d %d", position, y, x)
samuraiSudoku.mu.Unlock()
return false
}
//logger.Printf("%s: released lock, %d, %d", position, y, x)
samuraiSudoku.mu.Unlock()
}
}
//samuraiSudoku.mu.Unlock()
return true
}
func WriteGraph(samurai *SamuraiSudoku) {
stats := samurai.tracker.moves
var xValues []float64
var yValues []float64
startingTime := samurai.tracker.moves[0].time
for i, stat := range stats {
xValues = append(xValues, float64(stat.time.Sub(startingTime).Nanoseconds()))
yValues = append(yValues, float64(i))
}
timeGraph := chart.Chart{
Title: "Time (ms) and number of moves",
XAxis: chart.XAxis{
ValueFormatter: func(v interface{}) string {
return strconv.FormatInt(int64(v.(float64)/1000000), 10)
},
},
Series: []chart.Series{
chart.ContinuousSeries{
XValues: xValues,
YValues: yValues,
},
},
}
f, _ := os.Create("output.png")
defer f.Close()
timeGraph.Render(chart.PNG, f)
}
func WriteMultiThreadedGraph(samurai *SamuraiSudoku) {
stats := samurai.tracker.moves
var xValues []float64
var yValues []float64
startingTime := samurai.tracker.moves[0].time
for i, stat := range stats {
xValues = append(xValues, float64(stat.time.Sub(startingTime).Nanoseconds()))
yValues = append(yValues, float64(i))
}
timeGraph := chart.Chart{
Title: "Time (ms) and number of moves",
XAxis: chart.XAxis{
ValueFormatter: func(v interface{}) string {
return strconv.FormatInt(int64(v.(float64)/1000000), 10)
},
},
Series: []chart.Series{
chart.ContinuousSeries{
XValues: xValues,
YValues: yValues,
},
},
}
f, _ := os.Create("output.png")
defer f.Close()
timeGraph.Render(chart.PNG, f)
}