Workshop › Sudoku › Step 12 of 28
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
}
```br, bc are the top-left cell of the box: r - (r % 3) rounds down to 0, 3 or 6.i walks the row (board[r][i]), the column (board[i][c]) and the box, whose cell number i becomes a
row Math.floor(i / 3) and a column i % 3 inside the box.Under let selected, write the comment and canPlace.
Skills: Functions, Loops
← Write digits Show mistakes →