Workshop › Sudoku › Step 21 of 28

Invent a puzzle

What we are doing

Now the computer invents puzzles: make a random full grid, then empty cells in random order. After each removal, check with the solver that the puzzle still has exactly one solution; if not, put the digit back.

```js
const HOLES = 50 // how many cells are emptied

const copy = (board) => board.map((row) => row.slice())

// A random full grid, then empty cells one by one, keeping only removals that leave exactly one solution.
function makePuzzle() {
  const full = Array.from({ length: 9 }, () => Array(9).fill(0))
  countSolutions(full, 1, true)
  const puzzle = copy(full)
  let removed = 0
  for (const cell of shuffle([...Array(81).keys()])) {
    if (removed === HOLES) break
    const r = Math.floor(cell / 9)
    const c = cell % 9
    const digit = puzzle[r][c]
    puzzle[r][c] = 0
    if (countSolutions(copy(puzzle), 2) === 1) removed++
    else puzzle[r][c] = digit // two solutions: put it back
  }
  return { puzzle, full }
}
```

What it means

Your turn

  1. Under TOP, write HOLES.
  2. Under shuffle, write copy, the comment and makePuzzle.

Skills: Functions, Loops

All steps

  1. Nine by nine
  2. Lines and boxes
  3. A puzzle from a string
  4. The puzzle's own digits
  5. Keep drawing
  6. The selected cell
  7. Light up row, column and box
  8. The same digit everywhere
  9. Click to select
  10. Move with the arrows
  11. Write digits
  12. The three rules in one loop
  13. Show mistakes
  14. Solved!
  15. A clock
  16. The solved message
  17. Play again
  18. The easiest cell
  19. The solver
  20. Random order
  21. Invent a puzzle
  22. A new puzzle every game
  23. Hints
  24. Best time
  25. N for a new puzzle
  26. A number pad
  27. Tap the pad
  28. Build it yourself: undo