-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.rkt
65 lines (54 loc) · 2.04 KB
/
sudoku.rkt
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
#lang rosette/safe
;; An example game from https://en.wikipedia.org/wiki/Sudoku
;; 0 means blank and is to be filled
(define game '([5 3 0 0 7 0 0 0 0]
[6 0 0 1 9 5 0 0 0]
[0 9 8 0 0 0 0 6 0]
[8 0 0 0 6 0 0 0 3]
[4 0 0 8 0 3 0 0 1]
[7 0 0 0 2 0 0 0 6]
[0 6 0 0 0 0 2 8 0]
[0 0 0 4 1 9 0 0 5]
[0 0 0 0 8 0 0 7 9]))
;; every cell is between 1 and 9
(define game*
(map (λ (row)
(map (λ (cell)
(cond
[(zero? cell)
(define-symbolic* x integer?)
(assert (<= 1 x 9))
x]
[else cell]))
row))
game))
;; every row has distinct numbers
(for-each (λ (row) (assert (apply distinct? row))) game*)
;; every column has distinct numbers
;; = every row in the transposed game has distinct numbers
(define (transpose xs) (apply map list xs))
(for-each (λ (row) (assert (apply distinct? row))) (transpose game*))
;; every "group" has distinct numbers
(define (get-cell x y) (list-ref (list-ref game* y) x))
(define (get-group x y)
(list (get-cell (+ (* 3 x) 0) (+ (* 3 y) 0))
(get-cell (+ (* 3 x) 1) (+ (* 3 y) 0))
(get-cell (+ (* 3 x) 2) (+ (* 3 y) 0))
(get-cell (+ (* 3 x) 0) (+ (* 3 y) 1))
(get-cell (+ (* 3 x) 1) (+ (* 3 y) 1))
(get-cell (+ (* 3 x) 2) (+ (* 3 y) 1))
(get-cell (+ (* 3 x) 0) (+ (* 3 y) 2))
(get-cell (+ (* 3 x) 1) (+ (* 3 y) 2))
(get-cell (+ (* 3 x) 2) (+ (* 3 y) 2))))
(assert (apply distinct? (get-group 0 0)))
(assert (apply distinct? (get-group 1 0)))
(assert (apply distinct? (get-group 2 0)))
(assert (apply distinct? (get-group 0 1)))
(assert (apply distinct? (get-group 1 1)))
(assert (apply distinct? (get-group 2 1)))
(assert (apply distinct? (get-group 0 2)))
(assert (apply distinct? (get-group 1 2)))
(assert (apply distinct? (get-group 2 2)))
(define sol (solve #t))
(displayln "solution:")
(for-each println (evaluate game* sol))