Last active
April 20, 2024 18:41
-
-
Save leomastoras/64a5bf31ffa3f55afcf35fb2d2e7df5e to your computer and use it in GitHub Desktop.
Solve sudoku
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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