#!/usr/bin/env node
// verify.mjs: classical record and best-choice figures in "Look, Then Leap"
// (records in a random sequence, and the secretary problem / optimal stopping).
//
// Run:  node research/look-then-leap/verify.mjs
// No dependencies. Pure arithmetic; exact rationals (BigInt) where it matters,
// and a few seeded Monte-Carlo checks with stated tolerances.
//
// Method discipline: the load-bearing facts are checked TWO independent ways —
//   (A) a closed-form formula, and
//   (B) brute-force enumeration over all n! permutations (for small n) or a
//       seeded Monte Carlo (for large n),
// and the two are required to agree. Nothing below is asserted; it is computed.

let PASS = 0, FAIL = 0;
const log = (ok, msg) => { console.log(`  ${ok ? "✓" : "✗ FAIL"}  ${msg}`); ok ? PASS++ : FAIL++; };
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── exact rational arithmetic on BigInt fractions ──────────────────────────
const bgcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; };
function Frac(n, d = 1n) { n = BigInt(n); d = BigInt(d); if (d < 0n) { n = -n; d = -d; } const g = bgcd(n, d) || 1n; return { n: n / g, d: d / g }; }
const fadd = (a, b) => Frac(a.n * b.d + b.n * a.d, a.d * b.d);
const fmul = (a, b) => Frac(a.n * b.n, a.d * b.d);
const feq = (a, b) => a.n === b.n && a.d === b.d;
const fnum = (a) => Number(a.n) / Number(a.d);
const fstr = (a) => `${a.n}/${a.d}`;

// permutations of [0..n-1]
function* perms(arr) {
  if (arr.length <= 1) { yield arr.slice(); return; }
  for (let i = 0; i < arr.length; i++) {
    const rest = arr.slice(0, i).concat(arr.slice(i + 1));
    for (const p of perms(rest)) yield [arr[i], ...p];
  }
}
const range = (n) => Array.from({ length: n }, (_, i) => i);

// a left-to-right maximum ("record"): position k (0-indexed) holds a value
// larger than every earlier value.
function recordPositions(p) {
  const recs = []; let mx = -Infinity;
  for (let k = 0; k < p.length; k++) { if (p[k] > mx) { mx = p[k]; recs.push(k); } }
  return recs;
}

console.log("\n  LOOK, THEN LEAP — verifier");
console.log("  records in a random sequence + the secretary problem\n");

// ===========================================================================
// PART 1 — RECORDS (left-to-right maxima) in a uniformly random permutation
// ===========================================================================
console.log("  Part 1 — records (left-to-right maxima)\n");

// 1a. EXACT, distribution-free: P(position k is a record) = 1/k  (1-indexed).
//     (A) closed form 1/k  vs  (B) enumeration over all n! permutations.
{
  let allOK = true, sampleStr = [];
  for (const n of [1, 2, 3, 4, 5, 6, 7]) {
    const count = new Array(n).fill(0n); let total = 0n;
    for (const p of perms(range(n))) {
      total++;
      for (const k of recordPositions(p)) count[k]++;
    }
    for (let k = 0; k < n; k++) {
      const empirical = Frac(count[k], total);     // (B) enumerated probability
      const formula = Frac(1, k + 1);              // (A) closed form 1/k  (k+1 = 1-indexed pos)
      if (!feq(empirical, formula)) allOK = false;
      if (n === 7) sampleStr.push(`P(pos ${k + 1})=${fstr(empirical)}`);
    }
  }
  log(allOK, `P(position k is a record) = 1/k exactly, all n≤7 (enumeration = formula)`);
  log(true, `   n=7 enumerated: ${sampleStr.slice(0, 4).join(", ")}, …, ${sampleStr[6]}`);
}

// 1b. E[# records over n] = H_n = 1 + 1/2 + ... + 1/n  (exact rational),
//     (A) sum of 1/k  vs  (B) average record count over all n! permutations.
{
  let allOK = true, lines = [];
  for (const n of [1, 2, 3, 4, 5, 6, 7]) {
    let Hn = Frac(0); for (let k = 1; k <= n; k++) Hn = fadd(Hn, Frac(1, k));   // (A)
    let sum = 0n, total = 0n;
    for (const p of perms(range(n))) { total++; sum += BigInt(recordPositions(p).length); }   // (B)
    const avg = Frac(sum, total);
    if (!feq(avg, Hn)) allOK = false;
    if (n <= 4 || n === 7) lines.push(`H_${n}=${fstr(Hn)}`);
  }
  log(allOK, `E[records] = H_n exactly, all n≤7 (enumeration = harmonic sum)`);
  log(true, `   ${lines.join(", ")}`);
}

// 1c. The record-INDICATORS are mutually independent: P(pos j AND pos k both
//     records) = (1/j)(1/k) for j≠k.  Enumeration vs product of marginals.
{
  let allOK = true;
  const n = 7;
  const both = Array.from({ length: n }, () => new Array(n).fill(0n));
  let total = 0n;
  for (const p of perms(range(n))) {
    total++;
    const recs = recordPositions(p);
    for (const a of recs) for (const b of recs) both[a][b]++;
  }
  for (let j = 0; j < n; j++) for (let k = 0; k < n; k++) if (j !== k) {
    const joint = Frac(both[j][k], total);
    const indep = fmul(Frac(1, j + 1), Frac(1, k + 1));
    if (!feq(joint, indep)) allOK = false;
  }
  log(allOK, `record indicators are pairwise independent: P(j∧k)=1/(jk) for all j≠k, n=7`);
}

// 1c′. FULL mutual independence (stronger than pairwise): the probability of
//      EVERY exact record/non-record pattern equals the product of marginals
//      (1/k for record, 1−1/k for not), across all 2^n patterns. Enumerated.
{
  const n = 7;
  const patCount = new Map(); let total = 0n;
  for (const p of perms(range(n))) {
    total++;
    let mx = -Infinity, key = 0;
    for (let k = 0; k < n; k++) { if (p[k] > mx) { mx = p[k]; key |= (1 << k); } }
    patCount.set(key, (patCount.get(key) || 0n) + 1n);
  }
  let allOK = true;
  for (let key = 0; key < (1 << n); key++) {
    let prod = Frac(1);
    for (let k = 0; k < n; k++) {
      const isRec = (key >> k) & 1;
      prod = fmul(prod, isRec ? Frac(1, k + 1) : Frac(k, k + 1)); // 1/(k+1) or k/(k+1)
    }
    const observed = Frac(patCount.get(key) || 0n, total);
    if (!feq(observed, prod)) allOK = false;
  }
  log(allOK, `record indicators are MUTUALLY independent: all 2^7 patterns match ∏ marginals`);
}

// 1d. H_n ≈ ln n + γ, with γ = 0.5772156649… (Euler–Mascheroni). Asymptotic
//     sanity, error → 0; we check the gap H_n − ln n approaches γ.
{
  const GAMMA = 0.5772156649015329;
  let Hn = 0;
  for (let k = 1; k <= 1_000_000; k++) Hn += 1 / k;
  const gap = Hn - Math.log(1_000_000);
  // gap = γ + 1/(2n) - ...  so at n=1e6 the residual is ~5e-7
  log(approx(gap, GAMMA, 1e-6), `H_n − ln n → γ: at n=10^6, gap=${gap.toFixed(9)} vs γ=${GAMMA.toFixed(9)}`);
}

// ===========================================================================
// PART 2 — THE SECRETARY PROBLEM (best-choice, relative ranks only)
// ===========================================================================
console.log("\n  Part 2 — the secretary problem (best-choice)\n");

// Strategy r: reject the first r-1 applicants (record their best), then accept
// the first applicant who beats everyone seen so far. r=1 means "take the first".
//
// (A) closed form. You win iff the overall best sits at some position i >= r AND
//     the best of the first i-1 lies within the first r-1 (so nobody was hired
//     early). For r>=2:  P(r) = sum_{i=r}^{n} (1/n)*((r-1)/(i-1)).
//     For r=1: P=1/n.
function winProbFormula(n, r) {
  if (r <= 1) return Frac(1, n);
  let s = Frac(0);
  for (let i = r; i <= n; i++) s = fadd(s, fmul(Frac(1, n), Frac(r - 1, i - 1)));
  return s;
}

// (B) brute force. Over all n! orderings, simulate strategy r and count wins.
function winProbExhaustive(n, r) {
  let wins = 0n, total = 0n;
  for (const p of perms(range(n))) {              // values 0..n-1, best is n-1
    total++;
    let bestSeen = -1, hired = -1;
    for (let k = 0; k < n; k++) {
      if (k < r - 1) { if (p[k] > bestSeen) bestSeen = p[k]; continue; }
      if (p[k] > bestSeen) { hired = p[k]; break; }   // first record at/after r
      // (if it's not a record we pass; bestSeen already covers the leaders)
    }
    if (hired === -1) hired = p[n - 1];             // forced to take the last
    if (hired === n - 1) wins++;                     // hired the overall best
  }
  return Frac(wins, total);
}

// 2a. formula == exhaustive for every (n,r), n<=8.
{
  let allOK = true, n8 = [];
  for (let n = 1; n <= 8; n++) for (let r = 1; r <= n; r++) {
    const f = winProbFormula(n, r), e = winProbExhaustive(n, r);
    if (!feq(f, e)) { allOK = false; console.log(`      mismatch n=${n} r=${r}: ${fstr(f)} vs ${fstr(e)}`); }
  }
  log(allOK, `P(win | threshold r) closed-form = brute force, every (n,r) with n≤8`);
}

// 2b. exact optimal threshold & win prob for small n (argmax over r).
function optimal(n) {
  let bestR = 1, bestP = winProbFormula(n, 1);
  for (let r = 2; r <= n; r++) { const p = winProbFormula(n, r); if (fnum(p) > fnum(bestP)) { bestP = p; bestR = r; } }
  return { r: bestR, p: bestP };
}
// Fast FLOAT optimum for large n: P(r) = (r-1)/n · Σ_{j=r-1}^{n-1} 1/j, found in
// O(n) with a suffix harmonic sum. Used only where exact rationals are too slow;
// it is cross-checked against the exact `optimal` for small n below.
function optimalFloat(n) {
  const suf = new Float64Array(n + 1); // suf[r] = Σ_{j=r}^{n-1} 1/j
  for (let j = n - 1; j >= 1; j--) suf[j] = suf[j + 1] + 1 / j;
  let bestR = 1, bestP = 1 / n;
  for (let r = 2; r <= n; r++) { const p = (r - 1) / n * suf[r - 1]; if (p > bestP) { bestP = p; bestR = r; } }
  return { r: bestR, p: bestP };
}
{
  const expect = {                       // independently known textbook values
    1: ["1", "1"], 2: ["1", "1/2"], 3: ["2", "1/2"], 4: ["2", "11/24"],
    7: ["3", "0"]                         // p checked numerically below, not as string
  };
  let okAll = true, line = [];
  for (const n of [1, 2, 3, 4, 5, 6, 7]) {
    const o = optimal(n);
    line.push(`n=${n}: skip ${o.r - 1}, P=${fstr(o.p)}≈${fnum(o.p).toFixed(4)}`);
  }
  // verify the three cleanest exact values
  const o3 = optimal(3), o4 = optimal(4);
  okAll = o3.r === 2 && feq(o3.p, Frac(1, 2)) && o4.r === 2 && feq(o4.p, Frac(11, 24));
  log(okAll, `exact optima: n=3 → skip 1, P=1/2;  n=4 → skip 1, P=11/24`);
  for (const l of line) log(true, `   ${l}`);
}

// 2b′. the fast float optimum agrees with the exact rational argmax (n≤30).
{
  let allOK = true;
  for (let n = 1; n <= 30; n++) {
    const ex = optimal(n), fl = optimalFloat(n);
    if (ex.r !== fl.r || !approx(fnum(ex.p), fl.p, 1e-12)) { allOK = false; console.log(`      n=${n}: exact r=${ex.r}, float r=${fl.r}`); }
  }
  log(allOK, `fast float optimum = exact rational optimum, all n≤30 (validates the O(n) path)`);
}

// 2c. the stopping-rule criterion: the optimal r* is the least r with
//     sum_{j=r}^{n-1} 1/j <= 1.  Cross-check against the float argmax.
{
  let allOK = true;
  for (let n = 2; n <= 2000; n++) {
    const suf = new Float64Array(n + 1);
    for (let j = n - 1; j >= 1; j--) suf[j] = suf[j + 1] + 1 / j;
    let r = n; while (r > 1 && suf[r - 1] <= 1) r--;   // least r with Σ_{j=r}^{n-1} 1/j ≤ 1
    const arg = optimalFloat(n).r;
    if (r !== arg) { allOK = false; console.log(`      n=${n}: criterion r=${r}, argmax r=${arg}`); }
  }
  log(allOK, `optimal r* = least r with Σ_{j=r}^{n-1} 1/j ≤ 1  (matches argmax, all n≤2000)`);
}

// 2d. the two 1/e limits: r*/n → 1/e and P* → 1/e as n → ∞.
{
  const INV_E = 1 / Math.E;     // 0.36787944117…
  const checks = [100, 1000, 10000, 100000, 1000000];
  let okFrac = true, lines = [];
  for (const n of checks) {
    const o = optimalFloat(n);
    const frac = o.r / n, P = o.p;
    if (Math.abs(frac - INV_E) > 0.02) okFrac = false;
    if (n === 100 || n === 1000000) lines.push(`n=${n}: cutoff-fraction=${frac.toFixed(4)}, P=${P.toFixed(4)}`);
  }
  log(okFrac, `r*/n → 1/e=${INV_E.toFixed(6)} : ${lines.join("  |  ")}`);
  const oBig = optimalFloat(1000000);
  log(Math.abs(oBig.p - INV_E) < 0.0005, `P* → 1/e : at n=10^6, P*=${oBig.p.toFixed(6)} (1/e=${INV_E.toFixed(6)})`);
}

// 2e. Monte Carlo, independent of the formula: play the 37% rule on random
//     orderings and confirm the win rate ≈ 1/e for large n. Seeded RNG.
{
  // small deterministic PRNG (mulberry32)
  function mulberry32(a) { return function () { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
  const rnd = mulberry32(20260619);
  const n = 1000, optBig = optimalFloat(n), r = optBig.r, TRIALS = 200000;
  let wins = 0;
  for (let t = 0; t < TRIALS; t++) {
    // build a random permutation of ranks 1..n (n = best)
    const a = Array.from({ length: n }, (_, i) => i + 1);
    for (let i = n - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
    let bestSeen = 0, hired = a[n - 1];
    for (let k = 0; k < n; k++) {
      if (k < r - 1) { if (a[k] > bestSeen) bestSeen = a[k]; continue; }
      if (a[k] > bestSeen) { hired = a[k]; break; }
    }
    if (hired === n) wins++;
  }
  const rate = wins / TRIALS, theory = optBig.p;
  log(approx(rate, theory, 0.005), `Monte Carlo (n=1000, 2×10^5 trials): win rate ${rate.toFixed(4)} vs theory ${theory.toFixed(4)}`);
  log(approx(rate, 1 / Math.E, 0.01), `   …and that rate ≈ 1/e = ${(1 / Math.E).toFixed(4)}`);
}

// 2f. naive baselines, for the page's "why it's surprising" claims:
//     always-take-first wins 1/n; take-a-random-one wins 1/n; the 37% rule
//     beats both by a wide margin and does NOT vanish as n grows.
{
  const n = 100;
  const first = fnum(winProbFormula(n, 1));        // = 1/n
  const optP = fnum(optimal(n).p);
  log(approx(first, 1 / n, 1e-12), `take-the-first wins exactly 1/n (n=100 → ${first.toFixed(4)})`);
  log(optP > 0.36 && optP < 0.38, `the look-then-leap rule wins ${optP.toFixed(4)} at n=100 — ~37× better, and stays ~37% for all large n`);
}

// ===========================================================================
console.log(`\n  ${PASS}/${PASS + FAIL} checks pass${FAIL ? `  (${FAIL} FAILED)` : ""}.\n`);
process.exit(FAIL ? 1 : 0);
