Skip to content

Commit

Permalink
Improved random sudoku generation by implementing the fisher-yates sh…
Browse files Browse the repository at this point in the history
…uffle algorithm
  • Loading branch information
danieldotwav committed Dec 4, 2023
1 parent 244f002 commit b1c7072
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions dlx-solver.js
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,14 @@ inputs.forEach(function (input) {
// Random Sudoku Generation
///////////////////////////////////

// Fisher-Yates shuffle algorithm for an unbiased shuffle
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}

function generateFullSolution() {
let board = new Array(SIZE).fill(0).map(() => new Array(SIZE).fill(0));

Expand All @@ -526,7 +534,10 @@ function generateFullSolution() {
return solveBoard(board, row, col + 1); // Skip filled cells
}

for (let num = 1; num <= SIZE; num++) {
let numbers = Array.from({ length: SIZE }, (_, i) => i + 1);
shuffleArray(numbers);

for (let num of numbers) {
if (isSafe(board, row, col, num)) {
board[row][col] = num;

Expand All @@ -537,7 +548,6 @@ function generateFullSolution() {
board[row][col] = 0; // Backtrack
}
}

return false;
}

Expand Down

0 comments on commit b1c7072

Please sign in to comment.