Skip to content

Instantly share code, notes, and snippets.

@lior-amsalem
Created October 17, 2021 18:40
Show Gist options
  • Save lior-amsalem/16d146a65070d955b2fc1f1586c0f167 to your computer and use it in GitHub Desktop.
Save lior-amsalem/16d146a65070d955b2fc1f1586c0f167 to your computer and use it in GitHub Desktop.
Sudoku is a game played on a 9x9 grid. The goal of the game is to fill all cells of the grid with digits from 1 to 9, so that each column, each row, and each of the nine 3x3 sub-grids (also known as blocks) contain all of the digits from 1 to 9.
/**
example:
validSolution([
[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]
]); // => true
**/
function checkList(row) {
let rowArr = row.filter((value, index, self) => {
return self.indexOf(value) === index
}).filter(v => v !== 0);
return rowArr.length === 9 ? true : false
}
function blockArea(board) {
let blockIsValid = false;
let block = [];
for(let a = 0; a < board.length; a+=3){
for(let b = 0; b < board.length; b+=3){
block = [
board[b][0+a], board[b][1+a], board[b][2+a],
board[b+1][0+a], board[b+1][1+a], board[b+1][2+a],
board[b+2][0+a], board[b+2][1+a], board[b+2][2+a]
];
blockIsValid = checkList(block);
}
if(!blockIsValid) {
break;
}
}
return blockIsValid;
}
function rowNColumn(board) {
let r = false;
for(let a = 0; a < board.length; a++){
let column = [];
r = checkList(board[a])
for(let b = 0; b < board.length; b++){
column.push(board[b][a]);
}
r = checkList(column)
}
return r;
}
function validSolution(board){
let isSudokuValid = false;
isSudokuValid = rowNColumn(board);
if(isSudokuValid) {
isSudokuValid = blockArea(board);
}
return isSudokuValid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment