Sudoku Generator in JavaScript: From Swaps to Factorial Bijection
Game and app developers often face the challenge of generating unique Sudoku grids. Instead of tackling the NP-hard backtracking problem, a more efficient approach uses geometric transformations on a base valid grid. The algorithm evolved from simple array shuffling to a mathematical bijection that produces 609,492,049,920 unique configurations from a single template.
The base grid contains each digit 1–9 exactly once per row, column, and 3×3 block. Valid transformations preserve this invariant:
- Permuting rows within a 3×3 block
- Permuting columns within a 3×3 block
- Permuting row blocks (3×9)
- Permuting column blocks (9×3)
- Global digit permutation
First Iteration: Seeded Shuffling
The initial method used an 18-character hex seed to generate bits determining the sequence of swaps. The Mulberry32 algorithm provided a deterministic PRNG.
const BASE_GRID = [
[5,3,4, 6,7,8, 9,1,2],
[6,7,2, 1,9,5, 3,4,8],
[1,9,8, 3,4,2, 5,6,7],
[8,5,9, 7,6,1, 4,2,3],
[4,2,6, 8,5,3, 7,9,1],
[7,1,3, 9,2,4, 8,5,6],
[9,6,1, 5,3,7, 2,8,4],
[2,8,7, 4,1,9, 6,3,5],
[3,4,5, 2,8,6, 1,7,9]
];
const Utils = {
seededRandom: (seed) => {
return () => {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
},
hexToBits: (hex) => {
return [...hex].flatMap(char => {
const v = parseInt(char, 16);
return [(v >> 3) & 1, (v >> 2) & 1, (v >> 1) & 1, v & 1];
});
},
transforms: {
swapRows: (g, r1, r2) => { [g[r1], g[r2]] = [g[r2], g[r1]]; },
swapCols: (g, c1, c2) => {
for (let r = 0; r < 9; r++) [g[r][c1], g[r][c2]] = [g[r][c2], g[r][c1]];
},
swapRowBlocks: (g, b1, b2) => {
for (let i = 0; i < 3; i++) Utils.transforms.swapRows(g, b1 * 3 + i, b2 * 3 + i);
},
swapColBlocks: (g, b1, b2) => {
for (let i = 0; i < 3; i++) Utils.transforms.swapCols(g, b1 * 3 + i, b2 * 3 + i);
}
}
};
A 24-procedure swap array was applied in three passes using a bit mask derived from the seed. Issue: fixed digit patterns within blocks created visual repetition.
Second Iteration: Global Digit Swaps
Adding 8 swapDigits(d1, d2) transformations eliminated these patterns. The function scans the entire grid, swapping all instances of one digit with another:
swapDigits: (g, d1, d2) => {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (g[r][c] === d1) g[r][c] = d2;
else if (g[r][c] === d2) g[r][c] = d1;
}
}
}
Three passes with different offsets (0, 13, 29) modulo the procedure array length ensured chaotic behavior. Non-commutative operations guaranteed diversity.
Third Iteration: Factorial Bijection
The final version abandoned array mutations in favor of direct computation. Total unique transformations:
- Permuting 9 digits: 9! = 362,880
- Permuting 3 row blocks: 3! = 6
- Permuting 3 column blocks: 3! = 6
- Row permutations within 3 blocks: (3!)^3 = 216
- Column permutations within 3 blocks: (3!)^3 = 216
Total: 9! × 3! × 3! × (3!)^3 × (3!)^3 = 609,492,049,920
An 18-character hex seed is converted to BigInt, then modulo MAX_PERMUTATIONS. Number N is unpacked into factorial number system:
const Utils = {
getPermutation: (arr, k) => {
let available = [...arr];
let result = [];
let fact = 1;
for (let i = 2; i < available.length; i++) fact *= i;
for (let i = available.length - 1; i > 0; i--) {
const idx = Math.floor(k / fact);
result.push(available[idx]);
available.splice(idx, 1);
k %= fact;
fact /= i;
}
result.push(available[0]);
return result;
}
};
// In generate(seedStr):
const MAX_PERMUTATIONS = 609492049920n;
const seedBigInt = BigInt("0x" + clean);
let N = Number(seedBigInt % MAX_PERMUTATIONS);
const pDigits = Utils.getPermutation([1,2,3,4,5,6,7,8,9], N % 362880); N = Math.floor(N / 362880);
// ... remaining block and line permutations
For each cell [r][c], original coordinates are computed via block and intra-block permutation indices. Value is taken from BASE_GRID[oldR][oldC] and mapped through pDigits.
Key Advantages
- Determinism: One seed always generates one unique grid
- Efficiency: O(N) without array mutations—ideal for real-time generation
- Uniqueness: 6×10¹¹ variants eliminate collisions with 18-character seeds
- Validity: All transformations preserve Sudoku invariants
- Portability: Grid is fully determined by seed—perfect for player-to-player sharing
— Editorial Team
No comments yet.