aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/Saving.ts25
-rw-r--r--src/lib/Sudoku.ts58
2 files changed, 78 insertions, 5 deletions
diff --git a/src/lib/Saving.ts b/src/lib/Saving.ts
new file mode 100644
index 0000000..0d71057
--- /dev/null
+++ b/src/lib/Saving.ts
@@ -0,0 +1,25 @@
+import type { Grid } from "./Sudoku";
+
+export function save(grid: Grid) {
+ const a = document.createElement("a");
+ const fileParts = [JSON.stringify(grid)];
+ const blob = new Blob(fileParts, { type: 'application/json' }); // the blob
+ a.href = URL.createObjectURL(blob);
+ a.download = "sudoku-save.json";
+ a.click();
+}
+export function readGridFromFile(f: File): Promise<string[][] | null> {
+ return new Promise(res => {
+ let reader = new FileReader();
+ reader.onload = e => {
+ try {
+ //@ts-expect-error
+ const json = JSON.parse(e.target.result);
+ res(json)
+ } catch (error) {
+ res(null)
+ }
+ };
+ reader.readAsText(f);
+ })
+}
diff --git a/src/lib/Sudoku.ts b/src/lib/Sudoku.ts
index 0da0d77..94b972e 100644
--- a/src/lib/Sudoku.ts
+++ b/src/lib/Sudoku.ts
@@ -1,9 +1,57 @@
-import sudoku from "sudoku-umd";
+export type Grid = Array<Array<string>>;
+export type Coord = { x: number; y: number };
-type Grid = Array<Array<string>>;
+export function validate(board: Grid) {
+ const bads = [] as Coord[];
+ for (let i = 0; i < 9; i++) {
+ for (let j = 0; j < 9; j++) {
+ const value = board[i][j];
+ if (value !== '.') {
+ if (!validateRow(board, i, j, value) || !validateColumn(board, i, j, value) || !validateBox(board, i, j, value)) {
+ bads.push({ x: i, y: j })
+ }
+ }
+ }
+ }
+ return bads;
+};
-export function validate(grid: Grid) {
- const list = sudoku.board_grid_to_string(grid)
+function validateRow(board: Grid, row: number, col: number, value: string) {
+ for (let j = 0; j < 8; j++) {
+ if (j !== col) {
+ if (board[row][j] === value) {
+ return false;
+ }
+ }
+ }
- return true
+ return true;
+}
+
+function validateColumn(board: Grid, row: number, col: number, value: string) {
+ for (let i = 0; i < 8; i++) {
+ if (i !== row) {
+ if (board[i][col] === value) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+function validateBox(board: Grid, row: number, col: number, value: string) {
+ const startRow = row - (row % 3), startCol = col - (col % 3);
+
+ for (let i = startRow; i < startRow + 3; i++) {
+ for (let j = startCol; j < startCol + 3; j++) {
+ if (i !== row && j !== col) {
+ if (board[i][j] === value) {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
}