Sudoku

Random Sudoku generator

The question "how do you generate a Sudoku?" led me to write this simple random Sudoku generator, which also lets you play the puzzle right in the browser. The generator is written in TypeScript and the interface is built with React.

The initial idea was to find a mathematical algorithm to create a sequence of numbers (81 for a 9x9 grid) that satisfies the rules of Sudoku (numbers are never repeated within a row, a column, or a box), but despite several attempts and reading several articles on the subject, I could not find a satisfactory solution.

The game generates puzzles in real time with a backtracking algorithm, using the following process:

  • The generator creates a complete, valid grid;
  • The solver uses backtracking: it selects the empty cell with the fewest candidates, tries an allowed number, and continues. If it cannot find a solution, it backtracks and tries another choice;
  • Starting from the complete grid, the generator tries to remove one clue at a time, in random order. A removal is kept only if the solver confirms that the puzzle has exactly one solution;
  • The selected level determines the desired number of clues. The puzzle may retain more clues to guarantee a unique solution, including when the uniqueness check reaches its search limit.

Generation runs in a Web Worker to keep the interface responsive. Levels control the number of clues, rather than the logical techniques needed to solve the puzzle.

The game has the following features:

  • 4×4, 9×9, and 16×16 grids; in the latter, the letters A–G represent values from 10 to 16;
  • Selecting a cell and setting its value;
  • Adding and removing notes for each cell through note mode;
  • Shared history for numbers and notes, with the ability to undo and redo every action;
  • Four levels: easy, medium, hard, and expert;
  • Optional candidate display, highlighting the allowed numbers for the selected cell;
  • Optional error highlighting;
  • A timer that counts the time taken to complete the puzzle.

The game can be played right in the browser, on both desktop and mobile.

  • On desktop, select a cell by clicking it or using the arrow keys, then enter a number with the keyboard or the on-screen number pad. The Note mode button, or the N key, toggles notes; Shift + number enters a note directly. Delete/Backspace clears the cell. Ctrl/⌘ Z undoes an action, while Ctrl/⌘ Shift Z or Ctrl Y redoes it;
  • On mobile, tap a cell and enter a number with the on-screen number pad. With Note mode enabled, the same buttons add or remove notes. Buttons are also available to clear, undo, and redo.

Error and candidate preferences can be changed without losing the current game; changing the grid size or level generates a new puzzle. The game stays in memory until the page is reloaded.

The game is available at this address.