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);
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) {
sudoku[slot.y][slot.x] = 0;
i = i - 1;
continue;
}
sudoku[slot.y][slot.x] = sudoku[slot.y][slot.x] + 1;
if (
valid_row(sudoku, slot)
&& valid_col(sudoku, slot)
&& valid_square(sudoku, slot)
) {
i = i + 1;
}
}
console.assert(