← All lints

subset_masks_by_hand

L0585Idiomswarn

Subsets as masks, elements picked bit by bit

for mask in 0..(1 << n) testing (mask >> i) & 1 to pick a[i]: for sub in a.subsequences()

Flagged
let n: 1..=20 = read()
let a: [0..n]Int = read()
var best = 0
for mask in 0..(1 << n):
    let s = sum(a[i] for i in 0..n if mask.bit(i))
    if s % 3 == 0:
        best max= s
print(best)
Write instead
let n: 1..=20 = read()
let a: [0..n]Int = read()
var best = 0
for sub in a.subsequences():
    let s = sub.items.sum()
    if s % 3 == 0:
        best max= s
print(best)

Why

Walking mask over 0..(1 << n) and testing (mask >> i) & 1 to pick a[i] enumerates every subset of a, one bit at a time: O(2n⋅n)O(2^n \cdot n), with a shift, a mask and a bit test to get right. for sub in a.subsequences() (std.seq) walks the same subsets with sub.items the chosen elements, in O(k)O(k) per subset, and sub.prune() skips every extension of the current one, which a mask loop cannot do. Keep the mask where it is itself the answer or a DP index (dp[mask]); a loop over masks that never picks elements by bit is not reported. There is no automatic fix, because whether the mask is still needed has to be read.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

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

Near miss
let n: 1..=20 = read()
let w: [0..(1 << n)]Int = read()
var dp = [0..(1 << n)] _ => 0
for mask in 0..(1 << n):
    dp[mask] = w[mask] + (if mask > 0: dp[mask & (mask - 1)] else: 0)
print(dp)
// A bit that chooses between two values, or feeds arithmetic, is not picking a subset.
let a: [0..n]Int = read()
let b: [0..n]Int = read()
var best = 0
for mask in 0..(1 << n):
    best max= sum(if ((mask >> i) & 1) == 0: a[i] else: b[i] for i in 0..n)
    let bit = (mask >> 0) & 1
    best max= bit * a[0]
print(best)

Turn it off

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

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