Skip to content

Instantly share code, notes, and snippets.

@thebkr7
Last active May 8, 2019 19:34
Show Gist options
  • Save thebkr7/5d6f2285b1a91ea1de10e60001d37d7a to your computer and use it in GitHub Desktop.
Save thebkr7/5d6f2285b1a91ea1de10e60001d37d7a to your computer and use it in GitHub Desktop.
SudokuSolver2.0
var board = [
[4, 5, '.', 8, '.', '.', 9, '.', '.'],
['.', 9, '.', '.', 5, 6, '.', '.', 4],
[1, '.', '.', '.', '.', '.', '.', '.', 7],
[2, 6, '.', 5, 4, '.', '.', 9, '.'],
['.', '.', 4, 1, '.', 2, 3, '.', '.'],
['.', 7, '.', '.', 6, 9, '.', 4, 8],
[7, '.', '.', '.', '.', '.', '.', '.', 9],
[8, '.', '.', 4, 9, '.', '.', 7, '.'],
['.', '.', 9, '.', '.', 3, '.', 2, 5],
]
const subgridUsedNumbers = (rowStartIndex, columnStartIndex, gameBoard) => {
let usedNumbers = [];
rowStartIndex *= 3;
columnStartIndex *= 3;
for (let i = rowStartIndex; i < rowStartIndex + 3; i++) {
for (let x = columnStartIndex; x < columnStartIndex + 3; x++) {
if (gameBoard[i][x] !== '.') {
usedNumbers.push(gameBoard[i][x]);
};
};
};
return usedNumbers;
};
const rowUsedNumbers = (rowIndex, gameBoard) => {
let usedNumbers = [];
for (let x = 0; x < 9; x++) {
if (gameBoard[rowIndex][x] !== '.') {
usedNumbers.push(gameBoard[rowIndex][x]);
};
};
return usedNumbers;
};
const columnUsedNumbers = (columnIndex, gameBoard) => {
let usedNumbers = [];
for (let x = 0; x < 9; x++) {
if (gameBoard[x][columnIndex] !== '.') {
usedNumbers.push(gameBoard[x][columnIndex]);
};
};
return usedNumbers;
};
const sudokuMagician = (gameBoard) => {
for (let i = 0; i < 9; i++) {
for (let x = 0; x < 9; x++) {
if (gameBoard[i][x] === '.') {
let usedGridNumbers = subgridUsedNumbers(Math.floor(i/3), Math.floor(x/3), gameBoard);
let usedRowNumbers = rowUsedNumbers(i, gameBoard);
let usedColumnNumbers = columnUsedNumbers(x, gameBoard);
let combinedNumbers = [].concat(usedGridNumbers, usedRowNumbers, usedColumnNumbers)
for (let y = 1; y <= 9; y++) {
let yFound = combinedNumbers.indexOf(y);
if (yFound < 0) {
gameBoard[i][x] = y;
if (sudokuMagician(gameBoard)) {
return true;
} else {
gameBoard[i][x] = '.';
};
};
};
return false;
};
};
};
return true;
};
sudokuMagician(board);
console.log(board);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment