Workshop › Sudoku › Step 23 of 28
Stuck? H fills in a cell from the solution: the selected one if it is wrong or empty, otherwise the first cell that is. Hints are counted.
```js
let hints
hints = 0
// A hint fills the selected cell (or the first empty one) from the solution.
function hint() {
if (won) return
let cell = grid[selected.r][selected.c] === solution[selected.r][selected.c] ? null : selected
for (let i = 0; i < 81 && !cell; i++) {
const r = Math.floor(i / 9)
const c = i % 9
if (grid[r][c] !== solution[r][c]) cell = { r, c }
}
if (!cell) return
selected = cell
grid[cell.r][cell.c] = solution[cell.r][cell.c]
hints += 1
checkWin()
}
else if (event.key === 'h' || event.key === 'H') hint()
```cell starts as null and the loop looks for the first cell that
differs from the solution.i < 81 && !cell stops the loop as soon as a cell is found.let won, write let hints; in reset, set it to 0.enter, write the comment and hint.keydown, add the H line at the end of the chain.Skills: Game states, Keyboard and mouse input
← A new puzzle every game Best time →