Frames

Sudoku Validation

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1const sudokuValidator = (grid: Array<Array<number>>) => {
2 for (let i = 0; i < grid.length; i += 1) {
3 const rowCheckSet = new Set();
4 const colCheckSet = new Set();
5 const gridCheckSet = new Set();
6 const originX = (i % 3) * 3;
7 const originY = Math.floor(i / 3) * 3;
8 for (let j = 0; j < grid[i].length; j += 1) {
9 const rowValue = grid[i][j];
10 const colValue = grid[j][i];
11 const gridValue = grid[originX + Math.floor(j / 3)][originY + (j % 3)];
12
13 if (rowValue + colValue + gridValue > 2) {
14 rowCheckSet.add(rowValue);
15 colCheckSet.add(colValue);
16 gridCheckSet.add(gridValue);
17 } else {
18 return false;
19 }
20 }
21 if (rowCheckSet.size < 9 || colCheckSet.size < 9 || gridCheckSet.size < 9) {
22 return false;
23 }
24 }
25 return true;
26};
27console.log(
28 sudokuValidator([
29 [5, 3, 4, 6, 7, 8, 9, 1, 2],
30 [6, 7, 2, 1, 9, 5, 3, 4, 8],
31 [1, 9, 8, 3, 4, 2, 5, 6, 7],
32 [8, 5, 9, 7, 6, 1, 4, 2, 3],
33 [4, 2, 6, 8, 5, 3, 7, 9, 1],
34 [7, 1, 3, 9, 2, 4, 8, 5, 6],
35 [9, 6, 1, 5, 3, 7, 2, 8, 4],
36 [2, 8, 7, 4, 1, 9, 6, 3, 5],
37 [3, 4, 5, 2, 8, 6, 1, 7, 9],
38 ])
39);
40console.log(
41 sudokuValidator([
42 [5, 3, 4, 6, 7, 8, 9, 1, 2],
43 [6, 7, 2, 1, 9, 5, 3, 4, 8],
44 [1, 9, 8, 3, 4, 2, 5, 6, 7],
45 [8, 5, 9, 7, 2, 1, 4, 2, 3],
46 [4, 2, 6, 8, 5, 3, 7, 9, 1],
47 [7, 1, 3, 9, 2, 4, 8, 5, 6],
48 [9, 6, 1, 5, 3, 7, 2, 8, 4],
49 [2, 8, 7, 4, 1, 9, 6, 3, 5],
50 [3, 4, 5, 2, 8, 6, 1, 7, 9],
51 ])
52);
53