-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolver.js
More file actions
58 lines (54 loc) · 1.67 KB
/
solver.js
File metadata and controls
58 lines (54 loc) · 1.67 KB
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
let sudoku = [ [5, 3, 0, 0, 7, 0, 0, 0, 0,],
[6, 0, 0, 1, 9, 5, 0, 0, 0 ],
[0 ,9, 8, 0, 0, 0, 0, 6, 0 ],
[8, 0, 0, 0, 6, 0, 0, 0, 3 ],
[4, 0, 0, 8, 0, 3, 0, 0, 1 ],
[7, 0, 0, 0, 2, 0, 0, 0, 6 ],
[0, 6, 0, 0, 0, 0, 2, 8, 0 ],
[0, 0, 0, 4, 1, 9, 0, 0, 5 ],
[0, 0, 0, 0, 8, 0, 0, 7, 9 ] ];
const printSudoku = (sudoku) => {
document.write('<p></p>');
sudoku.forEach(row => {
document.write('<p style="font-size: 24px; margin-block-start: 0; margin-block-end: 0">');
row.forEach(number => {
document.write(number + " ");
})
document.writeln('</p>');
});
}
printSudoku(sudoku);
const possibleNumber = (x, y, n) => {
for (let i = 0; i < 9; i++) {
if (sudoku[y][i] == n) return false;
}
for (let i = 0; i < 9; i++) {
if (sudoku[i][x] == n) return false;
}
let x0 = (Math.floor(x/3)*3);
let y0 = (Math.floor(y/3)*3);
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (sudoku[y0 + i][x0 + j] == n) return false;
}
}
return true;
}
const solveSudoku = () => {
for (let y = 0; y < 9; y++) {
for (let x = 0; x < 9; x++) {
if (sudoku[y][x] == 0) {
for (let n = 1; n < 10; n++) {
if (possibleNumber(x, y, n)) {
sudoku[y][x] = n;
solveSudoku();
sudoku[y][x] = 0;
};
}
return;
}
}
}
printSudoku(sudoku);
}
solveSudoku();