Workshop › Candy Crush-style Match 3 › Step 10 of 29
findMatches finds every cell that is part of three or more of one color in a row or a column. From each cell it
looks right and down; it counts a run only from its first gem, and collects the cells in a Set.
```js
// Every cell that is part of three or more of the same color in a row or a column.
function findMatches() {
const cells = new Set()
for (let r = 0; r < N; r++) {
for (let c = 0; c < N; c++) {
const gem = board[r][c]
for (const [dr, dc] of [[0, 1], [1, 0]]) {
// Only start counting at the first gem of a run.
const pr = r - dr
const pc = c - dc
if (pr >= 0 && pc >= 0 && board[pr][pc] === gem) continue
let length = 1
while (r + dr * length < N && c + dc * length < N && board[r + dr * length][c + dc * length] === gem) length++
if (length >= 3) for (let i = 0; i < length; i++) cells.add((r + dr * i) * N + (c + dc * i))
}
}
}
return cells
}
```[dr, dc] is a direction: [0, 1] is right (same row, next column), [1, 0] is down.(pr, pc) is the cell just before this one in that direction. If it has the same color, this cell is inside a run
we already counted: continue skips it.while counts how far the color goes on; length++ adds one.r * N + c, because a Set compares objects
by identity, not content; a Set keeps each value once, so a gem in both a row and a column counts once.Write the comment and findMatches above function swap(a, b) {.
Skills: Arrays and objects, Loops
← Swap two neighbours No match, no swap →