~sschwarzer/sudoku-solver

sudoku-solver/games/sudoku-solver/solver.rkt -rw-r--r-- 19.8 KiB
fc2397a8Stefan Schwarzer Adapt artifacts for changed build target directory 3 months ago
                                                                                
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
#lang racket/base

(require racket/contract)

(provide
  (contract-out
    [make-board (-> (flat-named-contract 'list-of-81-cell-values list->board/c)
                    board?)]
    [board->string (-> board? string?)]
    ; `string->board` already contains some error checking code. A distinct predicate
    ; for the string would require to implement a good part of `string->board`.
    [string->board (-> string? board?)]
    [solve-board (-> board? solver-result?)]
    (struct solver-result ([board board?]
                           [duration flonum?]
                           [guesses-count integer?]
                           [progress-data progress-data?]))
  )
  EMPTY-CELL
)

(require
  racket/fixnum
  racket/format
  racket/list
  racket/string
  "progress-data.rkt"
)

; See https://en.wikipedia.org/wiki/Sudoku for the rules.

; --------------------------------------------------------------------------------
; Board representation, input and output

(define BOARD-WIDTH 9)
(define BOARD-HEIGHT 9)
(define BOARD-SIZE (* BOARD-WIDTH BOARD-HEIGHT))
(define REGION-WIDTH 3)
(define EMPTY-CELL -1)

; Fxvector
;
; Index -> board mapping:
;
;  0  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
(struct board (data)
  #:name Board
  #:constructor-name Board)

; Contract for the `make-board` input list
(define (list->board/c input)
  (and
    (= (length input) BOARD-SIZE)
    (for/and ([item input])
      (index-of (list 1 2 3 4 5 6 7 8 9 EMPTY-CELL) item eq?))))

; [List-of [Digit | EMPTY-CELL]] -> Board
;
; Return a `Board` with the data from the input list.
(define (list->board input)
  (Board (apply fxvector input)))

; [Optional List-of [Digit | EMPTY-CELL]] -> Board
;
; The values in the board vector must only be the fixnums 1 to 9 or `EMPTY-CELL`.
(define (make-board [input (make-list BOARD-SIZE EMPTY-CELL)])
  (list->board input))

; Board -> List
;
; Return a list with the data from the given `Board`.
(define (board->list board)
  (for/list ([item (in-fxvector (board-data board))])
    item))

; Board -> Board
;
; Create a new board with the same values of the `board` argument.
(define (board-copy board)
  (Board (fxvector-copy (board-data board))))

; --------------------------------------------------
; Board accessors

; Board Integer -> [Integer | EMPTY-CELL]
;
; Return value from `board` at `index`.
(define (board-ref board index)
  (fxvector-ref (board-data board) index))

; Board Integer [Integer | EMPTY-CELL] -> Board
;
; Functionally set `index` in board `board` to `value`. Return a new board.
(define (board-set board index value)
  (define new-vector (fxvector-copy (board-data board)))
  (fxvector-set! new-vector index value)
  (Board new-vector))

; Board Integer [Integer | EMPTY-CELL] -> Any
;
; Set `value` in-place.
(define (board-set! board index value)
  (fxvector-set! (board-data board) index value))

; --------------------------------------------------
; Board <-> string conversion

; String -> Board
;
; Convert a multi-line string like
;
; 53- -7- ---
; 6-- 195 ---
; -98 --- -6-
;
; 8-- -6- --3
; 4-- 8-3 --1
; 7-- -2- --6
;
; -6- --- 28-
; --- 419 --5
; --- -8- -79
;
; to a Sudoku board (created with `make-board`).
(define (string->board string)
  (define cleaned-string (regexp-replace* #px"\\s+" string ""))
  (make-board
    (for/list ([char cleaned-string])
      (cond
        [(and (char<=? #\1 char) (char<=? char #\9))
         (- (char->integer char) (char->integer #\0))]
        [(char=? char #\-)
         EMPTY-CELL]
        [else
         (raise-argument-error
           'string
           "string with digits 1-9, whitespace and \"-\""
           string)]))))

; Board -> String
;
; Convert a Sudoku board to a multi-line string.
(define (board->string board)
  (define (divisible-by value divisor)
    (= (remainder value divisor) 0))
  (define item-list
    (for/list ([index (in-range BOARD-SIZE)]
               [item (board-data board)])
      (define item-format
        (cond
          [(= index 0)                                       "~a"]
          ; Newline after three rows each
          [(divisible-by index (* REGION-WIDTH BOARD-WIDTH)) "\n\n~a"]
          ; Newline at end of row
          [(divisible-by index BOARD-WIDTH)                  "\n~a"]
          ; Space after each group of three digits
          [(divisible-by index REGION-WIDTH)                 " ~a"]
          [else                                              "~a"]))
      (define item-string
        (if (not (eq? item EMPTY-CELL))
            (~a item)
            "-"))
      (format item-format item-string)))
  (string-join item-list ""))

; --------------------------------------------------------------------------------
; Solver helpers

; Integer Integer -> Integer
;
; Round `index` down to multiples of `interval`.
;
; Examples:
; (floor-index 5 10) -> 0
; (floor-index 10 10) -> 10
; (floor-index 19 10) -> 10
; (floor-index 20 10) -> 20
(define (floor-index index interval)
  (* (quotient index interval) interval))

; Integer [List-of Integer] -> [List-of Integer]
;
; Return a list where each item is `start-index + item-offset`. The
; `start-index` is the upper-left corner of the row/column/region.
;
; Example:
; (index-range 2 '(2 3 7 8)) -> '(4 5 9 10)
(define (index-range start-index offsets)
  (for/list ([offset offsets])
    (+ start-index offset)))

; Integer -> [List-of Integer]
;
; Given an integer index in the board, return the indices for
; - the whole row
; - the whole column
; - the region
; the index argument is in.
(define (row-indices index)
  (define row-start-index (floor-index index BOARD-WIDTH))
  (index-range row-start-index '(0 1 2 3 4 5 6 7 8)))

(define (column-indices index)
  (define column-start-index (remainder index BOARD-WIDTH))
  (index-range column-start-index '(0 9 18 27 36 45 54 63 72)))

(define (region-indices index)
  (define column (remainder index BOARD-WIDTH))
  (define region-start-index (+ (floor-index index (* REGION-WIDTH BOARD-WIDTH))
                                (floor-index column REGION-WIDTH)))
  (index-range region-start-index '(0 1 2  9 10 11  18 19 20)))

; Return a true value if the `board` contains duplicated values at the
; `indices`.
;
; Examples:
; - The values `(list 1 2 3 8 EMPTY-CELL EMPTY-CELL 7 EMPTY-CELL 6) at the
;   indices would result in `#f` (no duplicates)
; - The values '(list 1 2 3 8 EMPTY-CELL EMPTY-CELL 7 EMPTY-CELL 3) at the
;   indices would result in `#t` (3 is duplicated)
(define (duplicates-at-indices? board indices)
  ; Use the _value_ retrieved at each `index` as the index into this vector.
  (define seen-flags (make-vector 10 #f))
  (let check-board-values ([board-indices indices])
    (cond
      [(empty? board-indices)
       ; We got to the end of the board indices without finding duplicates.
       #f]
      [else
       (define board-value (board-ref board (car board-indices)))
       (cond
         [(eq? board-value EMPTY-CELL)
          ; Skip empty cells when looking for duplicates.
          (check-board-values (cdr board-indices))]
         [(vector-ref seen-flags board-value)
          ; Flag already set; we found a duplicate.
          #t]
         [else
          ; Update flag and continue with next board index and value.
          (vector-set! seen-flags board-value #t)
          (check-board-values (cdr board-indices))])])))

; Board Integer -> Boolean
;
; Return true if the row/column/region that `index` belongs to is valid, i. e.
; doesn't contain duplicates.
(define (row-valid? board index)
  (not (duplicates-at-indices? board (row-indices index))))

(define (column-valid? board index)
  (not (duplicates-at-indices? board (column-indices index))))

(define (region-valid? board index)
  (not (duplicates-at-indices? board (region-indices index))))

; Board Integer -> Boolean
;
; Return true if the row, column and region that contain the `index` are valid,
; i. e. don't contain duplicates.
(define (index-valid? board index)
  (and (row-valid?    board index)
       (column-valid? board index)
       (region-valid? board index)))

; Board -> Boolean
;
; Check all rows, columns and regions to check if the board is valid.
;
; This is only intended to check the board once before starting the solver.
; During solving the board, we'll only check the row, column and region for the
; index where a new value is inserted.
(define (board-valid? board)
  (define rows-valid?
    (for/and ([index (in-range 0 BOARD-SIZE BOARD-WIDTH)])
      (row-valid? board index)))
  (define columns-valid?
    (for/and ([index (in-range BOARD-WIDTH)])
      (column-valid? board index)))
  (define regions-valid?
    ; Hardcode the indices of the upper-left corners of the regions instead of
    ; using a complicated calculation.
    (for/and ([index '(0 3 6  27 30 33  54 57 60)])
      (region-valid? board index)))
  (and rows-valid? columns-valid? regions-valid?))

; --------------------------------------------------------------------------------
; Solver

; Board -> [Integer | #f]
;
; Return next index with an `EMPTY-CELL` value, or `#f` if the board is
; complete.
(define (next-index-for-empty-cell board)
  (let find-empty-cell ([index 0])
    (cond
      [(= index BOARD-SIZE)                     #f]
      [(eq? (board-ref board index) EMPTY-CELL) index]
      [else                                     (find-empty-cell (add1 index))])))

; Board Flonum [Vector-of Integer]
;
; board: the solved board
; duration: solver runtime in seconds
; guesses-count: number of guesses taken to solve the board
; progress-data: `Progress-Data` instance
(struct solver-result
  (board duration guesses-count progress-data)
  ; FIXME Need to leave out `#:name` for now until
  ; https://github.com/racket/racket/issues/3791 is fixed.
  ; #:name Solver-Result
  #:constructor-name Solver-Result
  #:transparent)

; Board -> [Board | #f]
;
; Solve the Sudoku board `board` and return the solved board. If the board
; can't be solved, return `#f`.
(define (solve-board board)
  (unless (board-valid? board)
    (raise-argument-error
      'board
      "valid board"
      (board->string board)))
  (define start-time (current-inexact-milliseconds))
  (define guesses-count 0)
  (define progress-data (make-progress-data))
  (define result-board
    (let solve-board-iter ([board board]
                           [recursion-level 1])
      (define next-index (next-index-for-empty-cell board))
      (cond
        [(eq? next-index #f)
         ; Board complete
         board]
        [else
         (add-progress-record! progress-data recursion-level next-index BEFORE-GUESSES)
         ; Try to solve the board with numbers 1-9 at the missing index.
         (define new-candidate-board (board-copy board))
         (for/or ([guess (in-range 1 (add1 9))])
           (set! guesses-count (add1 guesses-count))
           (board-set! new-candidate-board next-index guess)
           (define board-valid? (index-valid? new-candidate-board next-index))
           (cond
             [board-valid?
              (add-progress-record! progress-data recursion-level next-index guess)
              (solve-board-iter new-candidate-board (add1 recursion-level))]
             [else
              #f]))])))
  (Solver-Result
    result-board
    (- (current-inexact-milliseconds) start-time)
    guesses-count
    progress-data))

; --------------------------------------------------------------------------------

(module+ test
  (require
    racket/function
    rackunit
    al2-test-runner)

    (define test-board-string
      "53- -7- ---
       6-- 195 ---
       -98 --- -6-

       8-- -6- --3
       4-- 8-3 --1
       7-- -2- --6

       -6- --- 28-
       --- 419 --5
       --- -8- -79")

    (define test-board-data
      (let ([EC EMPTY-CELL])
        (list
          5  3  EC   EC 7  EC   EC EC EC
          6  EC EC   1  9  5    EC EC EC
          EC 9  8    EC EC EC   EC 6  EC

          8  EC EC   EC 6  EC   EC EC  3
          4  EC EC   8  EC 3    EC EC  1
          7  EC EC   EC 2  EC   EC EC  6

          EC 6  EC   EC EC EC   2  8  EC
          EC EC EC   4  1  9    EC EC 5
          EC EC EC   EC 8  EC   EC 7  9)))

  (run-tests
    (test-suite "Board creation"
      (test-case
        "Empty board with `make-board`"
        (define empty-board (make-board))
        (define bd (board->list empty-board))
        (check-equal? bd (make-list BOARD-SIZE EMPTY-CELL)))
      (test-case
        "String to board"
        (define bd
          (board->list
            (string->board test-board-string)))
        (check-equal? bd test-board-data))
      (test-case
        "String to board with invalid characters in string"
        (define invalid-string
          ; Only 1-9 are valid digits.
          (string-replace test-board-string "9" "0"))
        (check-exn
          exn:fail:contract?
          (thunk (string->board invalid-string))))
      (test-case
        "Board to string"
        (define bs
          (board->string (Board test-board-data)))
        ; "Normalize" whitespace in strings so we can compare them.
        (check-equal? (regexp-replace* #px"\\s+" bs "x")
                      (regexp-replace* #px"\\s+" test-board-string "x")))
  ))

  (run-tests
    (test-suite "Board access"
      (test-case
        "`board-ref`"
        (define test-board (list->board test-board-data))
        (check-equal? (board-ref test-board 4)
                      7)
        (check-equal? (board-ref test-board 12)
                      1))
      (test-case
        "`board-set`"
        (define test-board (list->board test-board-data))
        (define new-board (board-set test-board 4 9))
        ; Original board should be unchanged.
        (check-equal? (board-ref test-board 4)
                      7)
        (check-equal? (board-ref new-board 4)
                      9))
  ))

  (define board-indices
    (range 0 BOARD-SIZE))

  (run-tests
    (test-suite "Index helper functions"
      (test-case
        "Row indices"
        (define result-indices
          (map row-indices board-indices))
        (define expected-result-indices
          (for*/list ([row (in-range BOARD-HEIGHT)]
                      [column (in-range BOARD-WIDTH)])
            (define start-index (* row BOARD-WIDTH))
            (range start-index (+ start-index BOARD-WIDTH))))
        (check-equal? result-indices expected-result-indices))
      (test-case
        "Column indices"
        (define result-indices
          (map column-indices board-indices))
        (define expected-result-indices
          (for*/list ([row (in-range BOARD-HEIGHT)]
                      [column (in-range BOARD-WIDTH)])
            (define start-index column)
            (range start-index (+ start-index BOARD-SIZE) BOARD-HEIGHT)))
        (check-equal? result-indices expected-result-indices))
      (test-case
        "Region indices"
        (define result-indices
          (map region-indices board-indices))
        (define (region-row-range start-index)
          (range start-index (+ start-index 3)))
        (define expected-result-indices
          (for*/list ([row (in-range BOARD-HEIGHT)]
                      [column (in-range BOARD-WIDTH)])
            (define start-index (+ (* (floor-index row 3) BOARD-WIDTH)
                                   (floor-index column 3)))
            (append
              (region-row-range (+ start-index (* 0 BOARD-WIDTH)))
              (region-row-range (+ start-index (* 1 BOARD-WIDTH)))
              (region-row-range (+ start-index (* 2 BOARD-WIDTH))))))
        (check-equal? result-indices expected-result-indices))
  ))

  (define completed-board
    (string->board
      ; Solution for `test-board-string` above, taken from Wikipedia article.
      "534 678 912
       672 195 348
       198 342 567

       859 761 423
       426 853 791
       713 924 856

       961 537 284
       287 419 635
       345 286 179"))

  (run-tests
    (test-suite "Solver"
      (test-case
        "Duplicates check"
        (define test-board (list->board test-board-data))
        (check-false (duplicates-at-indices? test-board (range 9 18)))
        (define new-board (board-set test-board 16 9))
        (check-true (duplicates-at-indices? new-board (range 9 18))))
      ; The following three tests check a specific index of the original board,
      ; which is valid. Then the tests modify the row/column/region the index
      ; belongs to so that the row/column/region contains duplicates and hence
      ; the tests for the index fail.
      (test-case
        "`row-valid?` and `index-valid?`"
        (define test-board (list->board test-board-data))
        ; Indices 12 and 16 are in the second row (1-based).
        (check-true (row-valid? test-board 12))
        (check-true (index-valid? test-board 12))
        (define new-board (board-set test-board 16 9))
        (check-false (row-valid? new-board 12))
        (check-false (index-valid? new-board 12)))
      (test-case
        "`column-valid?` and `index-valid?`"
        (define test-board (list->board test-board-data))
        ; Indices 12 and 30 are in the fourth column (1-based).
        (check-true (column-valid? test-board 12))
        (check-true (index-valid? test-board 12))
        (define new-board (board-set test-board 30 4))
        (check-false (column-valid? new-board 12))
        (check-false (index-valid? new-board 12)))
      (test-case
        "`region-valid?` and `index-valid?`"
        (define test-board (list->board test-board-data))
        ; Indices 12 and 23 are in the same region.
        (check-true (region-valid? test-board 12))
        (check-true (index-valid? test-board 12))
        (define new-board (board-set test-board 23 7))
        (check-false (region-valid? new-board 12))
        (check-false (index-valid? new-board 12)))
      (test-case
        "Invalid board"
        (define test-board (list->board test-board-data))
        (check-true (board-valid? test-board))
        (define new-board (board-set test-board 12 9))
        (check-false (board-valid? new-board)))

      (test-case
        "Solve invalid board"
        (define test-board (list->board test-board-data))
        (define new-board (board-set test-board 12 9))
        (check-exn exn:fail:contract?
                   (thunk (solve-board new-board))))
      (test-equal?
        "Solve completed board"
        (solver-result-board (solve-board completed-board))
        completed-board)
      (test-case
        "Solve almost complete board"
        (define incomplete-board (board-set completed-board 3 EMPTY-CELL))
        (check-equal? (board->list (solver-result-board (solve-board incomplete-board)))
                      (board->list completed-board)))
      (test-case
        "Solve board with three values missing"
        (define incomplete-board
          (board-set
            (board-set
              (board-set completed-board 3 EMPTY-CELL)
              12 EMPTY-CELL)
            70 EMPTY-CELL))
        (check-equal? (board->list (solver-result-board (solve-board incomplete-board)))
                      (board->list completed-board)))
      (test-case
        "Solve test board"
        (check-equal? (board->list (solver-result-board
                                     (solve-board (list->board test-board-data))))
                      (board->list completed-board)))
      (test-case
        "Solve empty board"
        (define empty-board (make-board (make-list BOARD-SIZE EMPTY-CELL)))
        (define expected-board
          (string->board "123 456 789
                          456 789 123
                          789 123 456
                          214 365 897
                          365 897 214
                          897 214 365
                          531 642 978
                          642 978 531
                          978 531 642"))
        (check-equal? (board->list (solver-result-board (solve-board empty-board)))
                      (board->list expected-board)))
  ))
)