Here is one way to implement an algorithm to check if a 9x9 grid is a valid sudoku board:
validSudokuTry in REPL1 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
| function isValid(grid) { return grid.every(checkRow) && transpose(grid).every(checkRow) && expandSubGrids(grid).every(checkRow); } function checkRow(row) { const tracker = new Set(); for (const cell of row) { if (cell !== '.' && tracker.has(cell)) { return false; } tracker.add(cell); } return true; } function expandSubGrids(grid) { const three = Math.sqrt(grid.length); return grid.map( (_,i) => grid.map( (_, j) => grid[(i/three|0)*three+j/three|0][i%three*three+j%three] ) ) } function transpose(grid) { return grid[0].map( (_, col) => grid.map(row => row[col]) ); }
|
Tests can be found at REPL.it