Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Readme

Brute Force Sudoku Solver

Solves Sudoku puzzles via backtracking search.

Pass in a 9x9 Sudoku puzzle array (of arrays) with 0's for empty slots. Returns a solved puzzle or null if the puzzle can't be solved.

Example example_val

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
// Brute Force Sudoku Solver
import { COLS, ROWS, Slot, Sudoku } from "https://esm.town/v/saolsen/sudoku";
type Index = { x: number; y: number };
function next_i(i: Index): Index | null {
if (i.x === COLS - 1 && i.y === ROWS - 1) {
return null;
}
if (i.x < COLS - 1) {
return { x: i.x + 1, y: i.y };
}
return { x: 0, y: i.y + 1 };
}
function valid_row(sudoku: Sudoku, i: Index): boolean {
const seen = new Set();
for (let col = 0; col < COLS; col++) {
const val = sudoku[i.y][col];
if (val !== 0) {
if (seen.has(val)) {
return false;
}
seen.add(val);
}
}
return true;
}
function valid_col(sudoku: Sudoku, i: Index): boolean {
const seen = new Set();
for (let row = 0; row < ROWS; row++) {
const val = sudoku[row][i.x];
if (val !== 0) {
if (seen.has(val)) {
return false;
}
seen.add(val);
}
}
return true;
}
function valid_square(sudoku: Sudoku, i: Index): boolean {
const col_offset = Math.floor(i.x / 3) * 3;
const row_offset = Math.floor(i.y / 3) * 3;
const seen = new Set();
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
const val = sudoku[row + row_offset][col + col_offset];
if (val !== 0) {
if (seen.has(val)) {
return false;
}
seen.add(val);
}
}
}
return true;
}
export function solve(sudoku: Sudoku): Sudoku | null {
sudoku = Sudoku.parse(sudoku);
// Collect list of empty slots to fill.
const slots: Index[] = [];
{
let slot: Index | null;
for (slot = { x: 0, y: 0 }; slot !== null; slot = next_i(slot)) {
if (sudoku[slot.y][slot.x] === 0) {
slots.push(slot);
}
}
}
let i: number = 0;
while (0 <= i && i < slots.length) {
const slot = slots[i];
if (sudoku[slot.y][slot.x] === 9) {
// no solution for this slot, clear and backtrack.
sudoku[slot.y][slot.x] = 0;
i = i - 1;
continue;
}
// pick next value
sudoku[slot.y][slot.x] = sudoku[slot.y][slot.x] + 1;
// check constraints
if (
valid_row(sudoku, slot)
&& valid_col(sudoku, slot)
&& valid_square(sudoku, slot)
) {
// move to next slot if valid
i = i + 1;
}
}
console.assert(
March 5, 2024