Workshop › Sudoku › Step 20 of 28

Random order

What we are doing

Solving an empty board gives a full, valid Sudoku grid, but always the same one. Shuffling the options makes the solver build a different random grid every time. This is the first half of inventing puzzles.

```js
// Counts solutions up to `limit`; `order` shuffles the digits to make random grids.
function countSolutions(board, limit = 2, order = false) {
  const cell = bestCell(board)
  if (!cell) return 1 // no empty cell left: solved
  const { r, c, options } = cell
  if (order) shuffle(options)
  let count = 0
  for (const d of options) {
    board[r][c] = d
    count += countSolutions(board, limit - count, order)
    if (count >= limit) return count // keep the board as it is: that is the solution
    board[r][c] = 0
  }
  return count
}

function shuffle(list) {
  for (let i = list.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[list[i], list[j]] = [list[j], list[i]]
  }
  return list
}
```

What it means

Your turn

  1. Change the second comment line and the function's first line to add order.
  2. Shuffle the options when order is on, and pass order along in the recursive call.
  3. Under countSolutions, write shuffle.

Skills: Arrays and objects

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