Skip to content

Instantly share code, notes, and snippets.

@leomastoras
Last active April 20, 2024 18:41
Show Gist options
  • Save leomastoras/64a5bf31ffa3f55afcf35fb2d2e7df5e to your computer and use it in GitHub Desktop.
Save leomastoras/64a5bf31ffa3f55afcf35fb2d2e7df5e to your computer and use it in GitHub Desktop.
Solve sudoku
// Sudoku solver
let Board = [
['5', '3', '.', '.', '7', '.', '.', '.', '.'],
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
['.', '.', '.', '.', '8', '.', '.', '7', '9'],
];
const sudoku = {
solve: function (row, col, board) {
if (col && !(col %= board[row].length) && ++row == board.length)
return true;
if (board[row][col] != '.')
return sudoku.solve(row, -~col, board);
for (let cval = 1; cval <= board.length; cval++)
if (
sudoku.putChar(row, col, board, cval + '') &&
sudoku.solve(row, -~col, board)
)
return true;
board[row][col] = '.';
return false;
},
putChar: (row, col, board, char) =>
![...Array(board.length).keys()].reduce(
(res, itr) =>
res ||
[
board[itr][col],
board[row][itr],
board[(row - (row % 3) + itr / 3) | []][col - (col % 3) + (itr % 3)],
].includes(char),
''
) && !!(board[row][col] = char),
};
const solveSudoku = board => sudoku.solve(0, 0, board);
solveSudoku(Board);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment