// Job #1843 (route 64): independent exact-max-coverage census over natal-survivor windows. // // Written this turn from the DEFINITION only (no code shared with job1838-ext.py, no masks or // tables reused from the record). Purpose: replicate or refute the Python census on the same // window range, and produce the per-window rigidity table for every near-miss. // // Object: natal survivors x = 6i+5 with no prime p in {5,...,37} dividing x or x+2; window j = the // 30 consecutive survivors xs[j..j+29]; scour primes Q = 41..73, one phase a_q per prime; slot i is // killed by q iff x == a_q or x+2 == a_q (mod q). capacity = sum_q max_a #killed by phase a; // max_cover = exact maximum killable by branch and bound with that admissible bound. // // Algorithmic difference from job1838-ext.py, on purpose: the search branches over the unused // primes in DYNAMIC order (descending max additional kills at the node), not in the fixed order // 41..73, and the bound is recomputed from the ordered list. Two implementations of the same // value with different search orders is a real cross-check; two copies of one is not. // // Deterministic: no timing in the artifact, no randomness, no iteration over hash maps. // Usage: kstar_census --lo J0 --hi J1 [--mincap 33] [--near 29] [--out FILE] // stdout is the artifact JSON; progress and timing go to stderr. use std::env; use std::fs; use std::process; use std::time::Instant; const Q: [usize; 9] = [41, 43, 47, 53, 59, 61, 67, 71, 73]; const L: usize = 30; const NQ: usize = 9; const PRIMES: [usize; 10] = [5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; const FULL: u64 = (1u64 << L) - 1; struct Args { lo: usize, hi: usize, mincap: u32, near: u32, out: Option, nodes_cap: u64, dump_window: Option, dump_masks: bool, } fn parse_args() -> Args { let mut a = Args { lo: 0, hi: 0, mincap: 33, near: 29, out: None, nodes_cap: u64::MAX, dump_window: None, dump_masks: false, }; let v: Vec = env::args().collect(); let mut i = 1; while i < v.len() { let key = v[i].as_str(); let val = || -> String { if i + 1 < v.len() { v[i + 1].clone() } else { eprintln!("{{\"error\":\"missing value for {}\"}}", key); process::exit(2); } }; match key { "--lo" => { a.lo = val().parse().unwrap(); i += 2; } "--hi" => { a.hi = val().parse().unwrap(); i += 2; } "--mincap" => { a.mincap = val().parse().unwrap(); i += 2; } "--near" => { a.near = val().parse().unwrap(); i += 2; } "--out" => { a.out = Some(val()); i += 2; } "--nodes-cap" => { a.nodes_cap = val().parse().unwrap(); i += 2; } "--dump-window" => { a.dump_window = Some(val().parse().unwrap()); i += 2; } "--dump-masks" => { a.dump_masks = true; i += 1; } _ => { eprintln!("{{\"error\":\"unknown arg {}\"}}", key); process::exit(2); } } } if a.hi == 0 || a.hi <= a.lo { eprintln!("{{\"error\":\"need --lo J0 --hi J1 with J1 > J0\"}}"); process::exit(2); } a } /// Sieve x = 6i+5 for i < n, keeping those with no p in PRIMES dividing x or x+2. fn survivors(n: usize) -> Vec { let mut ok = vec![true; n]; for &p in PRIMES.iter() { let inv = (1..p).find(|j| (6 * j) % p == 1).unwrap(); for b in [5usize, 7usize] { let first = ((p - (b % p)) * inv) % p; let mut i = first; while i < n { ok[i] = false; i += p; } } } let mut xs = Vec::with_capacity((n as f64 * 0.18) as usize + 64); for (i, v) in ok.iter().enumerate() { if *v { xs.push(6 * i as u64 + 5); } } xs } /// Per-prime kill bitmasks for window j. fn masks_for(xs: &[u64], j: usize) -> Vec> { let mut m = vec![vec![0u64; 73]; NQ]; for i in 0..L { let x = xs[j + i]; for k in 0..NQ { let q = Q[k] as u64; let r = (x % q) as usize; m[k][r] |= 1u64 << i; m[k][(r + 2) % (q as usize)] |= 1u64 << i; } } m } /// Exact max cover by branch and bound. Returns (best, phases, nodes, nodes-by-depth). /// /// Two ordering choices carry the whole cost of this search, and both were measured on the first /// capacity-33 window (start 2207) before being fixed here: /// * WITHIN a prime, branch phases by descending kill count. Omitting this sort does not change /// the value, but it does not let the incumbent reach 28 until late, after which nothing /// prunes: 101,114,414 nodes against 8,029, and the same failure is what makes a per-node /// reordering of the primes explode past 10^8 (probe_order.py variants A-E). /// * ORDER the primes statically by descending kills at cov = 0: 8,029 nodes here against /// 3,218 for the record's ascending 41..73 suffix order and 97,212 for descending. fn max_cover(m: &[Vec], cap: u64) -> (u32, Option<[usize; NQ]>, u64, [u64; NQ + 1]) { // Deduplicate phases by mask, keeping the smallest phase index (deterministic). let mut opts: Vec> = Vec::with_capacity(NQ); for k in 0..NQ { let mut seen: Vec<(u64, usize)> = Vec::new(); for a in 0..Q[k] { let mk = m[k][a]; if mk == 0 { continue; } if !seen.iter().any(|t| t.0 == mk) { seen.push((mk, a)); } } // descending kill count, ties by ascending phase index (Python's stable sort by // -popcount preserves the same tie order, so the two traversals are comparable node for // node: this was the missing half of the port) seen.sort_by(|x, y| y.0.count_ones().cmp(&x.0.count_ones()).then(x.1.cmp(&y.1))); opts.push(seen); } // Prime order: DESCENDING max kills at cov = 0, ties by prime index. This is the order that // made the tree small in probe_order.py variant E (2,373 nodes on the first capacity-33 window // against 3,218 for the record's ascending order, 97,212 for descending prime index, and // >10^8 for ANY order recomputed per node: the tree size is governed by when the incumbent // reaches 28, not by the bound's validity). The order is static per window so that the node // count here can be compared with the Python replica's on the same traversal. let root_top = |k: usize| -> u32 { opts[k].iter().map(|t| t.0.count_ones()).max().unwrap_or(0) }; let mut order: Vec = (0..NQ).collect(); order.sort_by(|&x, &y| root_top(y).cmp(&root_top(x)).then(x.cmp(&y))); let mut best: u32 = 0; let mut best_phases: Option<[usize; NQ]> = None; let mut cur = [0usize; NQ]; let mut nodes: u64 = 0; let mut full = false; let mut depth_nodes = [0u64; NQ + 1]; fn rec( i: usize, cov: u64, opts: &Vec>, order: &Vec, cur: &mut [usize; NQ], best: &mut u32, best_phases: &mut Option<[usize; NQ]>, nodes: &mut u64, depth_nodes: &mut [u64; NQ + 1], full: &mut bool, cap: u64, ) { *nodes += 1; depth_nodes[i] += 1; if *nodes >= cap { return; } let covered = cov.count_ones(); if covered > *best { *best = covered; *best_phases = Some(*cur); if covered as usize >= L { *full = true; return; } } if *full { return; } let rem = FULL & !cov; let mut bnd = covered; for j in i..NQ { let k = order[j]; let mut top = 0u32; for &(mk, _) in opts[k].iter() { let v = (mk & rem).count_ones(); if v > top { top = v; } } bnd += top; } if bnd <= *best { return; } let k = order[i]; for &(mk, a) in opts[k].iter() { cur[k] = a; rec(i + 1, cov | mk, opts, order, cur, best, best_phases, nodes, depth_nodes, full, cap); cur[k] = 0; if *full { return; } } } rec(0, 0, &opts, &order, &mut cur, &mut best, &mut best_phases, &mut nodes, &mut depth_nodes, &mut full, cap); (best, best_phases, nodes, depth_nodes) } /// Engine-free certificate: count killed slots by trial division, no masks. fn engine_free_kills(xs: &[u64], j: usize, phases: &[usize; NQ]) -> (u32, Vec) { let mut killed = Vec::new(); for i in 0..L { let x = xs[j + i]; let mut hit = false; for k in 0..NQ { let q = Q[k] as u64; let a = phases[k] as u64; if x % q == a || (x + 2) % q == a { hit = true; } } if hit { killed.push(i); } } (killed.len() as u32, killed) } fn jnum(v: &[u64]) -> String { v.iter().map(|n| n.to_string()).collect::>().join(",") } fn main() { let a = parse_args(); let t0 = Instant::now(); let n = ((a.hi as f64) * 5.9) as usize + 1000; let xs = survivors(n); if xs.len() < a.hi + L { eprintln!("{{\"error\":\"sieve too short\",\"have\":{},\"need\":{}}}", xs.len(), a.hi + L); process::exit(2); } eprintln!("{{\"stage\":\"sieved\",\"i_limit\":{},\"survivors\":{}}}", n, xs.len()); // sliding per-prime residue counts over the window let mut counts = vec![vec![0u32; 73]; NQ]; let mut mx = vec![0u32; NQ]; for k in 0..NQ { for i in 0..L { let x = xs[a.lo + i]; let q = Q[k] as u64; let r = (x % q) as usize; counts[k][r] += 1; counts[k][(r + 2) % q as usize] += 1; } mx[k] = *counts[k].iter().take(Q[k]).max().unwrap(); } let mut hist: Vec = vec![0; L + 2]; let mut analysed = 0u64; let mut total_nodes = 0u64; let mut depth_total = [0u64; NQ + 1]; let mut worst_nodes = 0u64; let mut worst_start = 0u64; let mut best = 0u32; let mut best_start = 0u64; let mut near: Vec = Vec::new(); let mut with_phases: Vec<(usize, u32, [usize; NQ], Vec)> = Vec::new(); let mut cover_found: Vec = Vec::new(); for j in a.lo..a.hi { if j > a.lo { for k in 0..NQ { let q = Q[k] as u64; let xo = xs[j - 1]; let xn = xs[j + L - 1]; let (r1, r2) = ((xo % q) as usize, ((xo + 2) % q) as usize); counts[k][r1] -= 1; counts[k][r2] -= 1; let (s1, s2) = ((xn % q) as usize, ((xn + 2) % q) as usize); counts[k][s1] += 1; counts[k][s2] += 1; mx[k] = *counts[k].iter().take(Q[k]).max().unwrap(); } } let cap: u32 = mx.iter().sum(); if cap < a.mincap { continue; } analysed += 1; let m = masks_for(&xs, j); let (val, phases, nodes, dprof) = max_cover(&m, a.nodes_cap); total_nodes += nodes; for d in 0..=NQ { depth_total[d] += dprof[d]; } if a.dump_masks { for k in 0..NQ { let mut seen: Vec = Vec::new(); for r in 0..Q[k] { let mk = m[k][r]; if mk != 0 && !seen.contains(&mk) { seen.push(mk); } } seen.sort_unstable(); println!("{}:{}", Q[k], seen.iter().map(|v| v.to_string()).collect::>().join(",")); } } if a.dump_window == Some(xs[j]) { eprintln!("{{\"stage\":\"dump\",\"start\":{},\"nodes\":{},\"value\":{},\"order\":[{}],\"depth_profile\":[{}],\"opts_lens\":[{}]}}", xs[j], nodes, val, { let rt = |k: usize| -> u32 { let mut top = 0u32; for a in 0..Q[k] { let v = m[k][a].count_ones(); if v > top { top = v; } } top }; let mut do_: Vec = (0..NQ).collect(); do_.sort_by(|&x, &y| rt(y).cmp(&rt(x)).then(x.cmp(&y))); do_.iter().map(|k| Q[*k].to_string()).collect::>().join(",") }, (0..=NQ).map(|d| depth_total[d].to_string()).collect::>().join(","), (0..NQ).map(|k| { let mut seen: Vec = Vec::new(); for r in 0..Q[k] { let mk = m[k][r]; if mk != 0 && !seen.contains(&mk) { seen.push(mk); } } seen.len().to_string() }).collect::>().join(",")); } if nodes > worst_nodes { worst_nodes = nodes; worst_start = xs[j]; } hist[val as usize] += 1; if val > best { best = val; best_start = xs[j]; eprintln!("{{\"stage\":\"new best\",\"max_cover\":{},\"start\":{},\"cap\":{}}}", val, xs[j], cap); } if val >= a.near { let ph = phases.unwrap(); let (killed, _) = engine_free_kills(&xs, j, &ph); assert_eq!(killed, val, "engine-free count disagrees at start {}", xs[j]); let xv: Vec = (0..L).map(|i| xs[j + i]).collect(); near.push(format!( "{{\"start\":{},\"window_index\":{},\"capacity\":{},\"max_cover\":{},\"phases\":{{{}}},\"engine_free_kills\":{}}}", xs[j], j, cap, val, (0..NQ).map(|k| format!("\"{}\":{}", Q[k], ph[k])).collect::>().join(","), killed)); if val as usize >= L { cover_found.push(format!( "{{\"start\":{},\"window_index\":{},\"slots\":[{}],\"phases\":{{{}}},\"engine_free_kills\":{}}}", xs[j], j, jnum(&xv), (0..NQ).map(|k| format!("\"{}\":{}", Q[k], ph[k])).collect::>().join(","), killed)); } else { with_phases.push((j, cap, ph, xv)); } } if analysed % 1000 == 0 { eprintln!("{{\"stage\":\"progress\",\"j\":{},\"analysed\":{},\"best\":{},\"s\":{:.1}}}", j, analysed, best, t0.elapsed().as_secs_f64()); } } let histtext = (0..hist.len()) .filter(|i| hist[*i] > 0) .map(|i| format!("\"{}\":{}", i, hist[i])) .collect::>() .join(","); // rigidity tables for every near-miss short of 30 let mut structs: Vec = Vec::new(); for (j, cap, ph, xv) in with_phases.iter() { // kills per prime, then private sets and marginal gains let mut kills: Vec> = Vec::new(); for k in 0..NQ { let q = Q[k] as u64; let a_ = ph[k] as u64; let mut v = Vec::new(); for (i, x) in xv.iter().enumerate() { if x % q == a_ || (x + 2) % q == a_ { v.push(i); } } kills.push(v); } let mut union: Vec = Vec::new(); for k in 0..NQ { for &i in kills[k].iter() { if !union.contains(&i) { union.push(i); } } } union.sort_unstable(); let mut uncovered: Vec = (0..L).filter(|i| !union.contains(i)).collect(); uncovered.sort_unstable(); let mut priv_counts: Vec = Vec::new(); for k in 0..NQ { let mut c = 0usize; for &i in kills[k].iter() { let mut elsewhere = false; for kk in 0..NQ { if kk != k && kills[kk].contains(&i) { elsewhere = true; } } if !elsewhere { c += 1; } } priv_counts.push(c); } let mut rows: Vec = Vec::new(); for &u in uncovered.iter() { let mut per: Vec = Vec::new(); for k in 0..NQ { let q = Q[k] as u64; // union of the OTHER primes let mut rest: Vec = Vec::new(); for kk in 0..NQ { if kk == k { continue; } for &i in kills[kk].iter() { if !rest.contains(&i) { rest.push(i); } } } let base_union = { let mut u2 = rest.clone(); for &i in kills[k].iter() { if !u2.contains(&i) { u2.push(i); } } u2.len() }; let x = xv[u]; let mut cand: Vec = vec![x % q, (x + 2) % q]; cand.sort_unstable(); cand.dedup(); let mut gains: Vec = Vec::new(); for &b in cand.iter() { let mut kb: Vec = Vec::new(); for (i, y) in xv.iter().enumerate() { if y % q == b || (y + 2) % q == b { kb.push(i); } } let mut u2 = rest.clone(); for &i in kb.iter() { if !u2.contains(&i) { u2.push(i); } } gains.push(format!("{}", u2.len() as i64 - base_union as i64)); } per.push(format!( "{{\"q\":{},\"chosen_phase\":{},\"chosen_kills\":{},\"chosen_private\":{},\"would_kill_phases\":[{}],\"marginal_gain\":[{}]}}", q, ph[k], kills[k].len(), priv_counts[k], cand.iter().map(|b| b.to_string()).collect::>().join(","), gains.join(","))); } rows.push(format!("{{\"slot\":{},\"value\":{},\"per_prime\":[{}]}}", u, xv[u], per.join(","))); } structs.push(format!( "{{\"start\":{},\"window_index\":{},\"capacity\":{},\"max_cover\":{},\"phases\":{{{}}},\"uncovered_slots\":[{}],\"private_slots_per_prime\":{{{}}},\"private_total\":{},\"rows\":[{}]}}", xv[0], j, cap, L - uncovered.len(), (0..NQ).map(|k| format!("\"{}\":{}", Q[k], ph[k])).collect::>().join(","), uncovered.iter().map(|i| i.to_string()).collect::>().join(","), (0..NQ).map(|k| format!("\"{}\":{}", Q[k], priv_counts[k])).collect::>().join(","), priv_counts.iter().sum::(), rows.join(","))); } let out = format!( "{{\"mode\":\"rust_census\",\"lo\":{},\"hi\":{},\"min_capacity\":{},\"near_threshold\":{},\"analysed\":{},\"total_nodes\":{},\"worst_nodes\":{},\"worst_start\":{},\"best_max_cover\":{},\"best_start\":{},\"slots_short_of_L\":{},\"max_cover_histogram\":{{{}}},\"near_miss_starts\":[{}],\"near_miss_structures\":[{}],\"cover_found\":[{}]}}\n", a.lo, a.hi, a.mincap, a.near, analysed, total_nodes, worst_nodes, worst_start, best, best_start, L as u32 - best, histtext, near.join(","), structs.join(","), cover_found.join(",")); if let Some(p) = a.out.as_ref() { fs::write(p, &out).unwrap_or_else(|e| { eprintln!("{{\"error\":\"write failed: {}\"}}", e); process::exit(2); }); } print!("{}", out); eprintln!("{{\"stage\":\"done\",\"analysed\":{},\"best\":{},\"nodes\":{},\"worst_nodes\":{},\"worst_start\":{},\"wall_s\":{:.1}}}", analysed, best, total_nodes, worst_nodes, worst_start, t0.elapsed().as_secs_f64()); }