Skip to content

Instantly share code, notes, and snippets.

@jayeshcp
Created October 23, 2020 15:29
Show Gist options
  • Save jayeshcp/08e1dc5fadea625443ea168a6724d822 to your computer and use it in GitHub Desktop.
Save jayeshcp/08e1dc5fadea625443ea168a6724d822 to your computer and use it in GitHub Desktop.
Soduku checker
// In this implementation it is assumed that grid is always 9x9
function sudoku2(grid) {
// check rows
for(let row = 0; row < grid.length; row++) {
const numbersMap = new Set();
for(let column = 0; column < grid[row].length; column++) {
if(grid[row][column] === ".") continue;
if (numbersMap.has(grid[row][column])) {
return false;
} else {
numbersMap.add(grid[row][column]);
}
}
}
// check columns
for(let column = 0; column < grid[0].length; column++) {
const numbersMap = new Set();
for(let row = 0; row < grid.length; row++) {
if(grid[row][column] === ".") continue;
if (numbersMap.has(grid[row][column])) {
return false;
} else {
numbersMap.add(grid[row][column]);
}
}
}
// check each 3x3 grid
for(let row = 0; row < grid.length; row += 3) {
for(let column = 0; column < grid[row].length; column += 3) {
const numbersMap = new Set();
for(let i = row; i < row + 3; i++) {
for(let j = column; j < column + 3; j++) {
if(grid[i][j] === ".") continue;
if (numbersMap.has(grid[i][j])) {
return false;
} else {
numbersMap.add(grid[i][j]);
}
}
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment