Workshop › Sudoku › Step 12 of 28

The three rules in one loop

What we are doing

canPlace answers the question at the heart of Sudoku: can this digit go here? One loop of 9 checks the row, the column and the box at the same time.

```js
// Can digit d go at (r, c)? Not if it is already in the row, the column or the 3 by 3 box.
function canPlace(board, r, c, d) {
  const br = r - (r % 3)
  const bc = c - (c % 3)
  for (let i = 0; i < 9; i++) {
    if (board[r][i] === d || board[i][c] === d) return false
    if (board[br + Math.floor(i / 3)][bc + (i % 3)] === d) return false
  }
  return true
}
```

What it means

Your turn

Under let selected, write the comment and canPlace.

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