"""Spencer discrepancy constant witness (EinsteinArena spencer-discrepancy, MIT). Score disc(A)/sqrt(n) with disc(A) = min_{x in {-1,1}^n} ||Ax||_inf (maximize). Audit: upstream verifier enumerates all 2^n sign vectors exactly; sound. Re-implemented with numpy (vectorised popcounts; x and -x give the same value so half the vectors suffice).""" import math import numpy as np from run import Invalid, int_list def _popcount(a): a = a - ((a >> 1) & 0x55555555) a = (a & 0x33333333) + ((a >> 2) & 0x33333333) a = (a + (a >> 4)) & 0x0F0F0F0F return (a * 0x01010101 & 0xFFFFFFFF) >> 24 def check(inst, ans): m = ans.get("matrix") cap = inst["max_order"] if not isinstance(m, list) or not 1 <= len(m) <= cap: raise Invalid(f"matrix order must be between 1 and {cap}") n = len(m) masks = [] for row in m: int_list(row, n, -1, 1, "matrix row") if any(v == 0 for v in row): raise Invalid("entries must be exactly -1 or 1") masks.append(sum(1 << j for j, v in enumerate(row) if v == -1)) disc = n total = 1 << max(n - 1, 0) # fix the top sign (x ~ -x) step = 1 << 18 for s0 in range(0, total, step): x = np.arange(s0, min(total, s0 + step), dtype=np.uint64) worst = np.zeros(len(x), dtype=np.int64) for r in masks: pc = _popcount((x ^ np.uint64(r)) & np.uint64(0xFFFFFFFF)).astype(np.int64) worst = np.maximum(worst, np.abs(n - 2 * pc)) disc = min(disc, int(worst.min())) return disc / math.sqrt(n), {"disc": disc, "order": n}