-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
did-i-finish-my-sudoku.js
77 lines (70 loc) · 1.98 KB
/
did-i-finish-my-sudoku.js
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
function isValid(numbers) {
// assumes numbers is an array of length 9
const seen = {};
for (let i = 0; i < numbers.length; i++) {
const value = numbers[i];
if (value <= 0 || value > 9) return false;
if (seen[value]) return false;
seen[value] = true;
}
return true;
}
function getSection(board, row, col) {
return board[row].slice(col, col + 3);
}
function getRegion(board, row, col) {
return [
...getSection(board, row, col),
...getSection(board, row + 1, col),
...getSection(board, row + 2, col),
];
}
function doneOrNot(board){
// check each row is valid
if (board.every(isValid)) {
// check each col is valid
for (let col = 0; col < 9; col++) {
if (!isValid(board.map(row => row[col]))) {
return 'Try again!';
}
}
// check each region is valid
for (let col = 0; col < 9; col += 3) {
for (let row = 0; row < 9; row += 3) {
if (!isValid(getRegion(board, row, col))) {
return 'Try again!';
}
}
}
} else {
return 'Try again!';
}
return 'Finished!';
}
function doneOrNot(board){
return (board.every(isValid)
&& Array.from({ length: 9 }).every((_, col) => isValid(board.map(row => row[col])))
&& [0, 3, 6].every(col => [0, 3, 6].every(row => isValid(getRegion(board, row, col))))) ? 'Finished!' : 'Try again!';
}
console.log(doneOrNot([
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
]), 'Finished!');
console.log(doneOrNot([
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 0, 3, 4, 9],
[1, 0, 0, 3, 4, 2, 5, 6, 0],
[8, 5, 9, 7, 6, 1, 0, 2, 0],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 0, 1, 5, 3, 7, 2, 1, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 0, 0, 4, 8, 1, 1, 7, 9]
]), 'Try again!');