@amanwebdev/sudoku-generator
v1.3.0
Published
Sudoku generator, solver, validator, gameplay toolkit, and PDF/image exporter
Maintainers
Readme
Sudoku Generator
A Node.js Sudoku generator, solver, validator, and gameplay toolkit for 4×4, 6×6, and 9×9 puzzles, with reproducible generation, compact serialization, and optional PDF/image renderers.
Requires Node.js 18 or newer.
Installation
npm install @amanwebdev/sudoku-generatorUsage
Basic Sudoku Generation
const { generateSudoku } = require('@amanwebdev/sudoku-generator');
// Generate a 9x9 Sudoku with easy difficulty
const sudoku = generateSudoku(9, 'easy');
console.log('Puzzle:');
console.log(sudoku.grid);
console.log('Solution:');
console.log(sudoku.solution);Pass a seed when you need reproducible output:
const sudoku = generateSudoku(9, 'medium', { seed: 12345 });Play, Solve, and Validate
const {
countSolutions,
getCandidates,
isValidMove,
solveSudoku,
stringToGrid,
validateSudoku
} = require('@amanwebdev/sudoku-generator/core');
const grid = stringToGrid(`
53..7....
6..195...
.98....6.
8...6...3
4..8.3..1
7...2...6
.6....28.
...419..5
....8..79
`);
const validation = validateSudoku(grid);
// { valid: true, complete: false, solvable: true, unique: true, conflicts: [] }
const candidates = getCandidates(grid, 0, 2); // [1, 2, 4]
const canPlaceFour = isValidMove(grid, 0, 2, 4); // true
const solution = solveSudoku(grid);
const solutionCount = countSolutions(grid); // 1 (checks up to 2 by default)All core utilities support 4×4, 6×6, and 9×9 grids and leave the input grid unchanged.
Serialize a Grid
const {
gridToString,
stringToGrid
} = require('@amanwebdev/sudoku-generator/core');
const encoded = gridToString([
[1, 0, 3, 0],
[0, 3, 0, 1],
[3, 0, 1, 0],
[0, 1, 0, 3]
]);
// "1.3..3.13.1..1.3"
const restored = stringToGrid(encoded);PDF Export
const { generateSudoku } = require('@amanwebdev/sudoku-generator/core');
const { toPDF } = require('@amanwebdev/sudoku-generator/pdf');
const fs = require('fs');
const sudoku = generateSudoku(9, 'easy');
// Generate puzzle PDF
const puzzlePdf = await toPDF(sudoku.grid, {
title: 'Sudoku Puzzle #1',
theme: 'light'
});
fs.writeFileSync('puzzle.pdf', puzzlePdf);
// Generate solution PDF with visual distinction
const solutionPdf = await toPDF(sudoku.grid, {
title: 'Sudoku Solution #1',
theme: 'light',
showSolution: true
}, sudoku.solution);
fs.writeFileSync('solution.pdf', solutionPdf);Image Export
const { generateSudoku } = require('@amanwebdev/sudoku-generator/core');
const { toImage } = require('@amanwebdev/sudoku-generator/image');
const fs = require('fs');
const sudoku = generateSudoku(9, 'medium');
// Generate puzzle image
const puzzleImage = toImage(sudoku.grid, {
theme: 'light',
cellSize: 80,
format: 'png'
});
fs.writeFileSync('puzzle.png', puzzleImage);
// Generate solution image with visual distinction
const solutionImage = toImage(sudoku.grid, {
theme: 'dark',
cellSize: 60,
format: 'jpeg',
quality: 0.9,
showSolution: true
}, sudoku.solution);
fs.writeFileSync('solution.jpg', solutionImage);API
generateSudoku(size, difficulty, options?)
Generates a new Sudoku puzzle.
Parameters:
size: The size of the Sudoku grid. Can be4,6, or9.difficulty: The difficulty of the puzzle. Can be'easy','medium', or'hard'.options.seed: Optional unsigned 32-bit integer for reproducible generation.
Difficulty controls clue-removal density while preserving a unique solution; it is not a rating of the logical techniques needed to solve the puzzle.
Returns: A Sudoku object with the following properties:
size: The size of the Sudoku grid.grid: A 2D array representing the puzzle (0 = empty cell).solution: A 2D array representing the complete solution.difficulty: The difficulty level used.
isValidMove(grid, row, column, value)
Checks whether value can be placed in an empty cell without violating row, column, or box rules.
grid: A 4×4, 6×6, or 9×9 matrix.rowandcolumn: Zero-based cell coordinates.value: An integer from1through the grid size.- Returns
truefor a legal placement. Occupied cells returnfalse.
The input grid is never mutated. Invalid coordinates, values, or grid shapes throw a TypeError.
getCandidates(grid, row, column)
Returns every legal value for an empty cell in ascending order.
grid: A 4×4, 6×6, or 9×9 matrix.rowandcolumn: Zero-based cell coordinates.- Returns
number[]. Occupied cells return an empty array.
solveSudoku(grid)
Solves a grid without mutating it.
grid: A 4×4, 6×6, or 9×9 matrix. Use0for empty cells.- Returns a completed
number[][], ornullwhen the givens conflict or no solution exists.
countSolutions(grid, limit?)
Counts solutions without mutating the grid. Search stops at limit, which defaults to 2; this makes uniqueness checks fast and avoids accidentally enumerating every solution of a sparse puzzle.
grid: A 4×4, 6×6, or 9×9 matrix.limit: Optional positive integer.- Returns the number found, capped at
limit. Conflicting givens return0.
validateSudoku(grid)
Inspects a grid and returns:
{
valid: boolean; // givens do not conflict
complete: boolean; // no empty cells remain
solvable: boolean; // at least one solution exists
unique: boolean; // exactly one solution exists
conflicts: Array<{
row: number; // zero-based
column: number; // zero-based
value: number;
type: 'row' | 'column' | 'box';
}>;
}Malformed matrices or cell values throw a TypeError. Sudoku rule violations are returned in conflicts.
gridToString(grid, emptyCell?)
Converts a grid to one compact row-major string. Empty cells use . by default; pass '-' or '0' to select another marker.
stringToGrid(value)
Parses a 16-, 36-, or 81-cell string and infers its Sudoku size. Whitespace is ignored, and ., -, and 0 are accepted as empty cells.
toPDF(grid, options?, solution?)
Exports a Sudoku grid to PDF format.
Parameters:
grid: A 2D number array representing the puzzle gridoptions: Optional PDF configuration objectsolution: Optional 2D number array for solution display (required whenshowSolution: true)
Options:
theme:'light'|'dark'| custom theme object (default:'light')title: PDF title text (default:'Sudoku Puzzle')author: PDF author metadata (default:'Sudoku Generator')subject: PDF subject metadata (default:'Sudoku Puzzle')keywords: PDF keywords metadata (default:'sudoku, puzzle, game')showSolution: Boolean to display solution with visual distinction (default:false)
Custom Theme:
{
background: '#ffffff',
gridColor: '#000000',
textColor: '#000000',
boxLineColor: '#000000'
}Returns: Promise<Uint8Array> - PDF file as bytes
toImage(grid, options?, solution?)
Exports a Sudoku grid to image format (PNG or JPEG).
Parameters:
grid: A 2D number array representing the puzzle gridoptions: Optional image configuration objectsolution: Optional 2D number array for solution display (required whenshowSolution: true)
Options:
theme:'light'|'dark'| custom theme object (default:'light')cellSize: Size of each cell in pixels (default:60)showSolution: Boolean to display solution with visual distinction (default:false)format:'png'|'jpeg'- Output image format (default:'png')quality: JPEG quality from 0 to 1 (default:0.95, only applies to JPEG format)
Returns: Buffer - Image file as bytes
Sample Output
Puzzle PDF
Clean, printable Sudoku puzzles with professional formatting:

Solution PDF
Solutions with visual distinction between given and solved digits:

Features
Core Utilities
- Generate: Create uniquely solvable 4×4, 6×6, and 9×9 puzzles
- Reproduce: Generate the same puzzle again with an unsigned 32-bit seed
- Play: Check moves and list candidates for empty cells
- Solve: Complete a puzzle without changing the caller's grid
- Validate: Detect row, column, and box conflicts with cell coordinates
- Inspect: Check completeness, solvability, uniqueness, and bounded solution counts
- Serialize: Convert grids to and from compact, shareable strings
PDF Export
- A4 Portrait Layout: Professional 210×297mm format
- Multiple Grid Sizes: Optimized layouts for 4×4, 6×6, and 9×9 grids
- Theme Support: Light, dark, and custom color themes
- Solution Display: Visual distinction between given and solved digits
- Metadata Support: Title, author, subject, and keywords
- Print Ready: Proper stroke weights and sizing for printing
Image Export
- Flexible Canvas Size: Configurable cell sizes for different output resolutions
- Multiple Formats: PNG and JPEG export with quality control
- Theme Support: Same theming system as PDF export
- Solution Overlay: Visual distinction between given and solved digits
- Server-side Rendering: Node.js canvas-based generation
- Scalable Output: Adjustable dimensions for web, print, or display use
Visual Design
- Given digits: Bold, full opacity
- Solution digits: Normal weight, lighter color for clear distinction
- Responsive sizing: Cell sizes adjust based on grid size
- Clean typography: Centered numbers with proper spacing
