← All lints

grid_neighbour_step

L0534Idiomswarn

Grid neighbour read behind a hand edge test

if r > 0: g[r - 1, c]: if let (pr, pc) = (r, c).step(Dir4.up())

Flagged
type Z = Mod<1_000_000_007>
let (h, w): (2..=1000, 2..=1000) = read()
let grid: [h, w]Char = read()
var ways: [h, w]Z = 0
ways[0, 0] = 1
for r in 0..h:
    for c in 0..w:
        if grid[r, c] == '#':
            continue
        if r > 0:
            ways[r, c] += ways[r - 1, c]
print(ways[h - 1, w - 1])
Write instead
type Z = Mod<1_000_000_007>
let (h, w): (2..=1000, 2..=1000) = read()
domain Row = 0..h
domain Col = 0..w
let grid: [Row, Col]Char = read()
var ways: [Row, Col]Z = 0
ways[0, 0] = 1
for (r, c) in (Row, Col):
    if grid[r, c] == '#':
        continue
    if let (pr, pc) = (r, c).step(Dir4.up):
        ways[r, c] += ways[pr, pc]
print(ways[Row(h - 1), Col(w - 1)])

Why

In C++ a grid is vector<vector<int>> indexed by plain ints, so every neighbour read needs its own edge test: if (r > 0) ways[r][c] += ways[r - 1][c]. Each test is one more place for an off-by-one, and nothing ties r > 0 to the r - 1 it protects. In CP Lang a grid is an array over two domains, [Row, Col]T with domain Row = 0..h, and (r, c).step(Dir4.up) from std.grid is the cell one step up or None when that step leaves the grid. if let (pr, pc) = (r, c).step(d): reads the neighbour only when it exists, so the edge test is gone, and Dir4.left, Dir4.down, Dir8 work the same way. The lint fires on if r > 0: (or r >= 1) whose body indexes a grid of two or more indices at r - 1. It has no fix, since the grid's declaration changes too.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.containers: deques, lists, grids, randomness.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let n: 1..=200000 = read()
let a: [0..n]Int = read()
var dp: [0..n]Int = 0
for i in 0..n:
    dp[i] = a[i]
    if i > 0:
        dp[i] += dp[i - 1]
print(dp[n - 1])

Turn it off

For one block, wrap it in with lint(grid_neighbour_step: allow):. For a project, add grid_neighbour_step = "allow" under [lints] in cp.toml.

Generated from spec/lints/grid_neighbour_step, the same record the linter is built from.