#!/usr/bin/env python3 # -*- coding: utf-8 -*- """cover90search.py — the search stage of job #2731. Objective (directly aligned with the assignment, and exactly checkable): f(V) = min over all window starts s of the number of holes in [s, s + 2454) computed on [0, X) by explicit per-offset coverage counts. f(V) = 0 IS a covered run of length >= 2454, i.e. exactly the base-10 bar; nothing is inferred from it. Soundness: the coverage count is a real per-offset count maintained by slice arithmetic on the moved prime's own residue classes (never an OR/XOR mask — the defect return #1137 convicted). Every value reported as a result is re-derived from scratch by `cover90.coverage` before it is written, and a witness is re-verified by an independent script (`cover90verify.py`). Metaheuristic: iterated local search — descent : for each prime, evaluate every residue (full sweep) and keep the best; kick : perturb a few primes at random, or restart from a fresh random tuple; accept : incumbent only. Plateau moves are allowed with a small probability so a sweep can walk across a flat region instead of stalling. A hole-driven move is also tried: pick a hole in the current best window and try the primes that can cover it (the residual-hole "closure" idea, but evaluated by damage). """ import argparse import json import time import numpy as np import cover90 as C from cover90 import PRIMES, N, classes R_TARGET = 2454 def score(cnt, X, R): """Holes in the best window of length R, and that window's start.""" holes = (cnt == 0) pref = np.concatenate((np.zeros(1, np.int32), np.cumsum(holes, dtype=np.int32))) w = pref[R:] - pref[:-R] i = int(np.argmin(w)) return int(w[i]), i def apply_move(cnt, k, v_old, v_new, X): p = PRIMES[k] for a in classes(p, v_old): cnt[a:X:p] -= 1 for a in classes(p, v_new): cnt[a:X:p] += 1 def build(res, X): cnt = C.coverage(res, X) return cnt def sweep(cnt, res, X, R, best_h, ties=0.0, rng=None): """One full coordinate-descent sweep. Returns (improved, best_h).""" improved = False for k in range(N): p = PRIMES[k] cur = res[k] for w in range(p): if w == cur: continue apply_move(cnt, k, cur, w, X) h, _s = score(cnt, X, R) take = h < best_h or (h == best_h and ties and rng.random() < ties) if take: best_h = h cur = w res[k] = w improved = True else: apply_move(cnt, k, w, cur, X) # if the sweep is already at the target there is nothing left to do return improved, best_h def hole_driven(cnt, res, X, R, best_h, s, rng): """Residual-hole closure attempt: take a hole inside the current best window and try every prime whose class can cover it, keeping the move that does the least damage.""" holes = np.flatnonzero(cnt[s:s + R] == 0) + s if len(holes) == 0: return False, best_h i = int(holes[int(rng.integers(0, len(holes)))]) improved = False for k in range(N): p = PRIMES[k] cur = res[k] for a in classes(p, cur): if (i - a) % p == 0: # this prime already covers the hole break else: w = (1 - i) % p # residue that makes p cover offset i apply_move(cnt, k, cur, w, X) h, _s = score(cnt, X, R) if h < best_h: best_h, res[k], improved = h, w, True else: apply_move(cnt, k, w, cur, X) return improved, best_h def run(X, R, seconds, seed, start, log): rng = np.random.default_rng(seed) res = list(start) cnt = build(res, X) best_h, best_s = score(cnt, X, R) best_res = list(res) t0 = time.time() it = kicks = restarts = 0 traj = [(0.0, best_h, best_s)] log({"event": "start", "holes": best_h, "start": best_s, "X": X, "R": R, "seed": seed, "residues": list(res)}) while time.time() - t0 < seconds: it += 1 # 1. descend _imp, h = sweep(cnt, res, X, R, best_h, ties=0.15, rng=rng) h, s = score(cnt, X, R) if h < best_h: best_h, best_s, best_res = h, s, list(res) traj.append((round(time.time() - t0, 2), h, s)) log({"event": "improve", "holes": h, "start": s, "iter": it, "t": round(time.time() - t0, 1), "residues": list(res)}) if h == 0: return best_res, 0, best_s, traj, it, kicks, restarts # 2. residual-hole closure on the incumbent's best window hole_driven(cnt, res, X, R, best_h, best_s, rng) h, s = score(cnt, X, R) if h < best_h: best_h, best_s, best_res = h, s, list(res) traj.append((round(time.time() - t0, 2), h, s)) log({"event": "improve_closure", "holes": h, "start": s, "iter": it, "t": round(time.time() - t0, 1), "residues": list(res)}) if h == 0: return best_res, 0, best_s, traj, it, kicks, restarts # 3. kick, or a fresh random plateau state if rng.random() < 0.30: res = [int(rng.integers(0, p)) for p in PRIMES] restarts += 1 log({"event": "restart_random", "iter": it, "t": round(time.time() - t0, 1)}) else: res = list(best_res) for _ in range(int(rng.integers(1, 6))): k = int(rng.integers(0, N)) res[k] = int(rng.integers(0, PRIMES[k])) kicks += 1 cnt = build(res, X) h2, s2 = score(cnt, X, R) if h2 < best_h: # a kick may already be an improvement best_h, best_s, best_res = h2, s2, list(res) traj.append((round(time.time() - t0, 2), h2, s2)) log({"event": "improve_kick", "holes": h2, "start": s2, "iter": it, "t": round(time.time() - t0, 1), "residues": list(res)}) if h2 == 0: return best_res, 0, best_s, traj, it, kicks, restarts return best_res, best_h, best_s, traj, it, kicks, restarts def main(): ap = argparse.ArgumentParser() ap.add_argument("--start") ap.add_argument("--X", type=int, default=4000) ap.add_argument("--R", type=int, default=R_TARGET) ap.add_argument("--seconds", type=float, default=300) ap.add_argument("--seed", type=int, default=1) ap.add_argument("--out", required=True) ap.add_argument("--log") a = ap.parse_args() fh = open(a.log, "w", encoding="utf-8") if a.log else None def log(rec): if fh: fh.write(json.dumps(rec) + "\n"); fh.flush() start = json.load(open(a.start)) if a.start else C.STATE_RESIDUES if isinstance(start, dict): start = start.get("best_residues") or start["residues"] t0 = time.time() res, h, s, traj, it, kicks, restarts = run(a.X, a.R, a.seconds, a.seed, start, log) # ---- re-derive the reported value FROM SCRATCH (never trust the incremental counter) cnt = C.coverage(res, a.X) pref = C.prefix_of(cnt) h_scratch, s_scratch = C.window_holes(pref, a.R, a.X) win = [int(i) for i in np.flatnonzero(cnt[s_scratch:s_scratch + a.R] == 0) + s_scratch] out = {"tool": "cover90search/1", "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "X": a.X, "R": a.R, "seconds_requested": a.seconds, "seconds_elapsed": round(time.time() - t0, 1), "seed": a.seed, "iterations": it, "kicks": kicks, "random_restarts": restarts, "start_residues": start, "best_residues": res, "best_window_holes_incremental": h, "best_window_holes_from_scratch": h_scratch, "best_window_start": s_scratch, "best_window_hole_list": win, "counter_matches_from_scratch": h == h_scratch, "found_witness": h_scratch == 0, "trajectory": traj} if h_scratch == 0: run_len, run_start = C.best_run(res, a.X) out["covered_run_in_range"] = {"length": run_len, "start": run_start} json.dump(out, open(a.out, "w", encoding="utf-8"), indent=1) if fh: fh.close() print(json.dumps({k: out[k] for k in ("best_window_holes_from_scratch", "counter_matches_from_scratch", "best_window_start", "best_window_hole_list", "found_witness", "iterations", "kicks", "random_restarts", "seconds_elapsed")}, indent=1)) return 0 if __name__ == "__main__": import sys sys.exit(main())