diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c4f831b606dd664f3d6490fd2973ea6c14ade01f --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "sudoku", + "version": "1.0.0", + "description": "To make it easy for you to get started with GitLab, here's a list of recommended next steps.", + "main": "solver.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "type": "module", + "author": "", + "license": "ISC" +} diff --git a/solver.js b/solver.js new file mode 100644 index 0000000000000000000000000000000000000000..232468dedab7b16b57cc2242e8408b3862fd1288 --- /dev/null +++ b/solver.js @@ -0,0 +1,66 @@ +function solveSudoku(board) { + const size = 9; + + function isValid(num, row, col) { + // Check if 'num' is not present in the current row, column, and 3x3 grid + for (let i = 0; i < size; i++) { + if ( + board[row][i] === num || + board[i][col] === num || + board[row - (row % 3) + Math.floor(i / 3)][col - (col % 3) + (i % 3)] === num + ) { + return false; + } + } + return true; + } + + function solve() { + for (let row = 0; row < size; row++) { + for (let col = 0; col < size; col++) { + if (board[row][col] === 0) { + for (let num = 1; num <= size; num++) { + if (isValid(num, row, col)) { + board[row][col] = num; + + if (solve()) { + return true; // If the current configuration leads to a solution + } + + // If the current configuration doesn't lead to a solution, backtrack + board[row][col] = 0; + } + } + return false; // If no number can be placed at this cell + } + } + } + return true; // If the entire board is filled + } + + if (solve()) { + return board; // Return the solved Sudoku board + } else { + return "No solution exists."; // Return a message if no solution exists + } + } + + // Example Sudoku board (0 represents empty cells) + const sudokuBoard = [ + [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], + ]; + + const solvedSudoku = solveSudoku(BoardArrayofArraysForLine); + console.log(solvedSudoku); + + + export {solveSudoku } + \ No newline at end of file diff --git a/test.js b/test.js deleted file mode 100644 index 28919f04e786202d33db07346cb620a27cbe1e65..0000000000000000000000000000000000000000 --- a/test.js +++ /dev/null @@ -1 +0,0 @@ -//dsaudiajkds \ No newline at end of file