Skip to content

Instantly share code, notes, and snippets.

@didagu
Created March 20, 2020 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save didagu/a676b5adbfd6ffc84ed46f0e222f2842 to your computer and use it in GitHub Desktop.
Save didagu/a676b5adbfd6ffc84ed46f0e222f2842 to your computer and use it in GitHub Desktop.
Simple Sudoku Solver using Back-Tracking Algorithm - Javascript version
const board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
];
function sudokuSolver(board) {
let nonPossibilities = {}, impossibleNumbers, emptySpaces = 1;
while (emptySpaces) {
emptySpaces = 0;
for (let vertical = 0; vertical < board.length; vertical++) {
for (let horizontal = 0; horizontal < board.length; horizontal++) {
if (board[vertical][horizontal] == 0) {
nonPossibilities = {};
for (let i = 0; i < 9; i++) {
//checkRow();
if (board[vertical][i] > 0) {
nonPossibilities[board[vertical][i]] = true;
}
//checkColumn();
if (board[i][horizontal] > 0) {
nonPossibilities[board[i][horizontal]] = true;
}
}
//checkBox();
for (let vBox = Math.floor(vertical / 3) * 3; vBox < Math.floor(vertical / 3) * 3 + 3; vBox++) {
for (let hBox = Math.floor(horizontal / 3) * 3; hBox < Math.floor(horizontal / 3) * 3 + 3; hBox++) {
if (board[vBox][hBox]) {
nonPossibilities[board[vBox][hBox]] = true;
}
}
}
impossibleNumbers = Object.keys(nonPossibilities);
if (impossibleNumbers.length === 8) { //then the 9th number is the possible one
for (let i = 1; i < 10; i++) {
if (impossibleNumbers.indexOf(i.toString()) < 0) {
board[vertical][horizontal] = i;
}
}
} else {
emptySpaces++;
}
}
}
}
}
return board;
}
console.log(sudokuSolver(board));
//result
// [
// [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]
// ];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment