-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku.nim
255 lines (217 loc) · 8 KB
/
sudoku.nim
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
import encodings
import cnf
import sequtils
import tables
import streams
import strformat
import strutils
import sugar
import utils
import intsets
type CellValue = tuple
row: int
col: int
num: int
type Sudoku* = object
size*: Natural
known*: seq[CellValue]
cellLookup*: Table[tuple[row, col: int], int]
rowLookup*: Table[tuple[row, num: int], int]
colLookup*: Table[tuple[col, num: int], int]
blockLookup*: Table[tuple[blk, num: int], tuple[row, col: int]]
proc literal(sudoku: Sudoku, cellValue: CellValue, negative: bool = false): Literal =
let base = sudoku.size * sudoku.size
result = cellValue.row - 1
result *= base
result += cellValue.col - 1
result *= base
result += cellValue.num - 1
result += 1 # 1-based
if negative:
result *= -1
proc cellValue(sudoku: Sudoku, literal: Literal): CellValue =
assert literal > 0
let base = sudoku.size * sudoku.size
var numLiteral : int = literal
numLiteral -= 1 # 0-based
let num = (numLiteral mod base) + 1
numLiteral = numLiteral div base
let col = (numLiteral mod base) + 1
numLiteral = numLiteral div base
let row = (numLiteral mod base) + 1
numLiteral = numLiteral div base
assert numLiteral == 0
return (row: row, col: col, num: num)
proc getBlockNum(row: int, col: int, size: Natural): int =
return ((row - 1) div size) * size + ((col - 1) div size) + 1
proc getBlockNum(sudoku: Sudoku, row: int, col: int): int =
return getBlockNum(row, col, sudoku.size)
proc getBlockStart(sudoku: Sudoku, row: int, col: int): tuple[row, col: int] =
let
blk = sudoku.getBlockNum(row, col) - 1
col = (blk mod sudoku.size) * sudoku.size + 1
row = (blk div sudoku.size) * sudoku.size + 1
return (row, col)
proc deserialize*(s: Stream): Sudoku =
var
line = ""
row = 0
col = 0
size = -1
known = newSeq[CellValue]()
cellLookup = initTable[tuple[row, col: int], int]()
rowLookup = initTable[tuple[row, num: int], int]()
colLookup = initTable[tuple[col, num: int], int]()
blockLookup = initTable[tuple[blk, num: int], tuple[row, col: int]]()
while s.readLine(line):
if line.startsWith("+"):
size = line.count('+') - 1
if line.startsWith("|"):
row += 1
col = 0
for token in line.split(Whitespace + {'|'}):
if token.len > 0: col += 1
if token.isDigit:
let num = token.parseInt
let blk = getBlockNum(row, col, size)
known.add((row, col, num))
cellLookup[(row, col)] = num
rowLookup[(row, num)] = col
colLookup[(col, num)] = row
blockLookup[(blk, num)] = (row, col)
assert size > 0
return Sudoku(
size: size,
known: known,
cellLookup: cellLookup,
rowLookup: rowLookup,
colLookup: colLookup,
blockLookup: blockLookup,
)
proc serialize*(sudoku: Sudoku, input: Stream, output: Stream) =
var
line = ""
n = sudoku.size * sudoku.size
maxLit = sudoku.literal((n,n,n))
board = newSeq[seq[int]](n)
for i in 0..<n:
board[i] = newSeq[int](n)
while input.readLine(line):
if line.startsWith("c ") or line.startsWith("s "):
log line
if line.startsWith("v "):
let positives = line
.substr(1)
.splitWhitespace()
.filter(proc (s: string) : bool = not s.startsWith('-') and not s.startsWith('0') and s.len > 0)
.map(parseInt)
for positive in positives:
if positive > maxLit: continue
let (row, col, num) = sudoku.cellValue(positive)
board[row - 1][col - 1] = num
for cellValue in sudoku.known:
let (row, col, num) = cellValue
board[row - 1][col - 1] = num
let digitWidth = log10(n)
let lineSeparator = ("+" & "-".repeat(1 + (digitWidth + 1) * sudoku.size)).repeat(sudoku.size) & "+"
for rowStart in countup(1, n, sudoku.size):
output.writeLine(lineSeparator)
for row in rowStart..<rowStart+sudoku.size:
for colStart in countup(1, n, sudoku.size):
output.write("| ")
for col in colStart..<colStart+sudoku.size:
var padded = ""
format(board[row - 1][col - 1], fmt"{digitWidth}", padded)
output.write(padded & " ")
output.writeLine("|")
output.writeLine(lineSeparator)
proc generateNegatives(sudoku: Sudoku): IntSet =
let n = sudoku.size * sudoku.size
result = initIntSet()
for cellValue in sudoku.known:
let (row, col, num) = cellValue
# cell
for lit in lc[sudoku.literal((row, col, i)) | (i <- 1..n, i != num), Literal]:
result.incl(lit)
# row
for lit in lc[sudoku.literal((row, i, num)) | (i <- 1..n, i != col), Literal]:
result.incl(lit)
# col
for lit in lc[sudoku.literal((i, col, num)) | (i <- 1..n, i != row), Literal]:
result.incl(lit)
# block
let blk = sudoku.getBlockStart(row, col)
for lit in lc[
sudoku.literal((x, y, num)) |
(
x <- blk.row..<blk.row+sudoku.size,
y <- blk.col..<blk.col+sudoku.size,
x != row,
y != col,
), Literal]:
result.incl(lit)
proc generateBaseCNF*(sudoku: Sudoku): Cnf =
let n = sudoku.size * sudoku.size
let numLiterals = n * n * n
var cnf = initCNF(numLiterals)
var pruned = 0
log "Generating negatives..."
let negatives = sudoku.generateNegatives()
log "Cell constraints..."
# cell constraints
for row in 1..n:
for col in 1..n:
if (row, col) in sudoku.cellLookup: continue
let clauses = cnf.exactlyOne(lc[
sudoku.literal((row, col, num)) |
(
num <- 1..n,
not negatives.contains(sudoku.literal((row, col, num)))
),
Literal])
for clause in clauses:
cnf.add(clause)
log "Row constraints..."
# row constraints
for row in 1..n:
for num in 1..n:
if (row, num) in sudoku.rowLookup: continue
let clauses = cnf.exactlyOne(lc[
sudoku.literal((row, col, num)) |
(
col <- 1..n,
not negatives.contains(sudoku.literal((row, col, num)))
), Literal])
for clause in clauses:
cnf.add(clause)
log "Col constraints..."
# col constraints
for col in 1..n:
for num in 1..n:
if (col, num) in sudoku.colLookup: continue
let clauses = cnf.exactlyOne(lc[
sudoku.literal((row, col, num)) |
(
row <- 1..n,
not negatives.contains(sudoku.literal((row, col, num)))
), Literal])
for clause in clauses:
cnf.add(clause)
log "Block constraints..."
# block constraints
for rowStart in countup(1, n, sudoku.size):
for colStart in countup(1, n, sudoku.size):
for num in 1..n:
let blk = sudoku.getBlockNum(rowStart, colStart)
if (blk, num) in sudoku.blockLookup: continue
let literals = lc[
sudoku.literal((row, col, num)) |
(
row <- rowStart..<(rowStart + sudoku.size),
col <- colStart..<(colStart + sudoku.size),
not negatives.contains(sudoku.literal((row, col, num)))
),
Literal]
for clause in cnf.exactlyOne(literals):
cnf.add(clause)
return cnf