-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgenerate_sudoku_v1.ts
91 lines (73 loc) · 2.02 KB
/
generate_sudoku_v1.ts
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
import { Set, Record, is, RecordOf } from 'immutable'
import fs from 'node:fs'
type Cell = RecordOf<{
x: number
y: number
}>
const makeCell = Record({ x: 0, y: 0 })
function range(start: number, end: number): number[] {
return [...Array(end - start + 1).keys()].map(i => i+start)
}
function* rowAt(y: number): Generator<Cell> {
for (const x of range(1, 9)) {
yield makeCell({ x, y })
}
}
function* columnAt(x: number): Generator<Cell> {
for (const y of range(1, 9)) {
yield makeCell({ x, y })
}
}
function* squareAt(topLeft: Cell): Generator<Cell> {
for (const x of range(topLeft.x, topLeft.x+2)) {
for (const y of range(topLeft.y, topLeft.y+2)) {
yield makeCell({ x, y })
}
}
}
function* allCells(): Generator<Cell> {
for (const y of range(1, 9)) {
for (const x of range(1, 9)) {
yield makeCell({ x, y })
}
}
}
function excludeListOf(cell: Cell): Set<Cell> {
const row = Set(rowAt(cell.y))
const column = Set(columnAt(cell.x))
const square = Set(squareAt(makeCell({
x: cell.x - (cell.x-1)%3,
y: cell.y - (cell.y-1)%3
})))
return row.union(column).union(square).delete(cell)
}
function showCell(cell: Cell): string {
return `X${cell.x}${cell.y}`
}
function showParamList(): string[] {
return [...allCells()].map(cell => `${showCell(cell)} extends Cell,`)
}
function showExcludeList(cell: Cell): string {
return [...excludeListOf(cell)].map(showCell).join(' | ')
}
function showGrid(): string[] {
return [...allCells()].map(cell => `Exclude<${showCell(cell)}, ${showExcludeList(cell)}>,`)
}
function unindent(count: number, str: string): string {
return str.split('\n').map(line => line.slice(count)).join('\n')
}
function showFile(): string {
const typeParams: string = ''
const grid: string = ''
return unindent(4, `
type Cell = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
export const sudoku = <
${showParamList().join('\n ')}
>(grid:
[
${showGrid().join('\n ')}
]
) => {}
`)
}
console.log(showFile())