Ternary search by hand
a while loop probing lo + (hi - lo) / 3 and hi - (hi - lo) / 3: ternary_min(lo..hi, f)!
let n: 1..=100000 = read()
let a: [0..n]Int = read()
fn cost(x: Int) -> Int = sum(abs(v - x) for v in a)
var lo = -1_000_000_000
var hi = 1_000_000_000
while hi - lo > 2:
let m1 = lo + (hi - lo) / 3
let m2 = hi - (hi - lo) / 3
if cost(m1) < cost(m2):
hi = m2
else:
lo = m1
print((lo..=hi).map(x => cost(x)).min()!)let n: 1..=100000 = read()
let a: [0..n]Int = read()
fn cost(x: Int) -> Int = sum(abs(v - x) for v in a)
let best = ternary_min(-1_000_000_000..1_000_000_001, cost)!
print(cost(best))Why
A loop that keeps lo and hi, probes two thirds lo + (hi - lo) / 3 and hi - (hi - lo) / 3, and drops the worse third is a ternary search for the extremum of a unimodal function. Written by hand it needs a stopping rule (hi - lo > 2) and a final scan of what is left, and either is easy to get wrong by one. ternary_min(lo..hi, f)! and ternary_max(lo..hi, f)! (std.search) return the position of the extremum over the range by golden-section search, which reuses one probe per step: about calls of f, fewer than the hand loop's . A loop that divides by 3 once per step, such as counting base-3 digits, is not reported. There is no automatic fix, because whether the loop wants the min or the max, and what it does with the range afterwards, 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.
let n: 1..=1000000 = read()
var x = n
var digits = 0
while x > 0:
x = (x - x % 3) / 3
digits += 1
print(digits)Turn it off
For one block, wrap it in with lint(ternary_search_by_hand: allow):. For a project, add ternary_search_by_hand = "allow" under [lints] in cp.toml.
Generated from spec/lints/ternary_search_by_hand, the same record the linter is built from.