summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas White <taw@physics.org>2022-04-03 22:49:18 +0200
committerThomas White <taw@physics.org>2022-04-03 22:49:18 +0200
commit6b5da750ef7134a108c6d996d14c2dd60fc62806 (patch)
tree6b0bd890b2382d0aa2c45f4a468c7d1688a351bc
parentd72557b139b3833e6bb4db16555a92821f084cbb (diff)
Add better read/write
-rw-r--r--sudoku.scm87
1 files changed, 58 insertions, 29 deletions
diff --git a/sudoku.scm b/sudoku.scm
index a92747b..446c420 100644
--- a/sudoku.scm
+++ b/sudoku.scm
@@ -2,6 +2,7 @@
(srfi srfi-1)
(srfi srfi-26)
(ice-9 match)
+ (ice-9 textual-ports)
(sat solver)
(sat helpers))
@@ -100,6 +101,59 @@
(iota 9))))
+(define (char->number c)
+ (match c
+ (#\0 0)
+ (#\1 1)
+ (#\2 2)
+ (#\3 3)
+ (#\4 4)
+ (#\5 5)
+ (#\6 6)
+ (#\7 7)
+ (#\8 8)
+ (#\9 9)))
+
+(define (process-line board row line)
+ (map
+ (lambda (c col)
+ (when (char-numeric? c)
+ (set-initial-value
+ board
+ col
+ row
+ (char->number c))))
+ (string->list line)
+ '(0 1 2 _ 3 4 5 _ 6 7 8)))
+
+
+(define (read-sudoku port board)
+ (process-line board 0 (get-line port))
+ (process-line board 1 (get-line port))
+ (process-line board 2 (get-line port))
+ (get-line port)
+ (process-line board 3 (get-line port))
+ (process-line board 4 (get-line port))
+ (process-line board 5 (get-line port))
+ (get-line port)
+ (process-line board 6 (get-line port))
+ (process-line board 7 (get-line port))
+ (process-line board 8 (get-line port)))
+
+
+(define (print-sudoku board vals)
+ (do ((row 0 (1+ row))) ((= row 9))
+ (do ((col 0 (1+ col))) ((= col 9))
+ (format #t "~a" (get-value board vals col row))
+ (when (or (= col 2)
+ (= col 5))
+ (display "|")))
+ (newline)
+ (when (or (= row 2)
+ (= row 5))
+ (display "-----------\n"))))
+
+
(let ((board (make-board)))
;; Each position contains exactly one number
@@ -113,34 +167,9 @@
(all-unique-values board (boxes))
;; Initially specified values
- (set-initial-value board 0 0 4)
- (set-initial-value board 0 7 5)
- (set-initial-value board 0 8 1)
-
- (set-initial-value board 1 1 3)
- (set-initial-value board 1 3 2)
-
- (set-initial-value board 2 8 4)
-
- (set-initial-value board 3 2 7)
- (set-initial-value board 3 6 6)
- (set-initial-value board 3 7 2)
-
- (set-initial-value board 4 4 8)
- (set-initial-value board 4 5 1)
-
- (set-initial-value board 5 6 3)
-
- (set-initial-value board 6 0 8)
- (set-initial-value board 6 4 4)
-
- (set-initial-value board 7 3 6)
- (set-initial-value board 7 6 7)
-
- (set-initial-value board 8 0 5)
+ (read-sudoku
+ (open-input-file "input.sudoku")
+ board)
(let ((vals (solve-sat)))
- (do ((row 0 (1+ row))) ((= row 9))
- (do ((col 0 (1+ col))) ((= col 9))
- (format #t "~a" (get-value board vals col row)))
- (newline))))
+ (print-sudoku board vals)))