#!/usr/bin/env node
// verify.mjs: independent one-copy calculations for "The Last One Is the Worst"
// (the coupon collector's problem: how long to collect a full set of n coupons,
//  drawn uniformly at random with replacement).
//
// Run:  node research/coupon-collector/verify.mjs
// No dependencies. Exact rationals (BigInt) where it matters; seeded Monte Carlo
// with stated tolerances elsewhere.
//
// Method discipline: the load-bearing facts are each checked TWO independent ways —
//   (A) a closed-form formula, and
//   (B) an absorbing-Markov-chain computation (exact) or a seeded Monte Carlo,
// 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 fsub = (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.d === 1n ? `${a.n}` : `${a.n}/${a.d}`;

// small deterministic PRNG (mulberry32) for reproducible Monte Carlo
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; }; }

console.log("\n  THE COUPON COLLECTOR — verifier");
console.log("  how long to collect a full set of n coupons (uniform, with replacement)\n");

// ===========================================================================
// PART 1 — THE EXPECTATION  E[T] = n·H_n
// ===========================================================================
console.log("  Part 1 — the expectation E[T] = n·H_n\n");

// (A) closed form: split the collection into phases. While you hold k distinct
//     coupons, the wait for a NEW one is Geometric with success prob (n−k)/n,
//     mean n/(n−k). Summing over k=0..n−1:  E[T] = Σ n/(n−k) = n·Σ_{j=1}^{n} 1/j
//     = n·H_n.
function expFormula(n) {
  let H = Frac(0); for (let j = 1; j <= n; j++) H = fadd(H, Frac(1, j));
  return fmul(Frac(n), H);   // n · H_n
}
// (B) absorbing Markov chain, exact. State = #distinct collected. From state k,
//     E[k] = 1 + (k/n)E[k] + ((n−k)/n)E[k+1]  ⇒  E[k] = n/(n−k) + E[k+1], E[n]=0.
//     This makes NO use of the closed form; it solves the recurrence bottom-up.
function expMarkov(n) {
  let E = Frac(0);                                    // E[n] = 0
  for (let k = n - 1; k >= 0; k--) E = fadd(Frac(n, n - k), E);
  return E;
}
{
  let allOK = true, lines = [];
  for (let n = 1; n <= 12; n++) {
    const a = expFormula(n), b = expMarkov(n);
    if (!feq(a, b)) allOK = false;
    if ([1, 2, 3, 6, 10].includes(n)) lines.push(`E[T_${n}]=${fstr(a)}≈${fnum(a).toFixed(3)}`);
  }
  log(allOK, `E[T] = n·H_n exactly, all n≤12 (phase-sum closed form = absorbing Markov chain)`);
  log(true, `   ${lines.join(", ")}`);
}

// (C) Monte Carlo, independent of both: simulate the collection and average T.
{
  const rnd = mulberry32(20260619);
  const n = 10, TRIALS = 400000;
  let sum = 0;
  for (let t = 0; t < TRIALS; t++) {
    const seen = new Uint8Array(n); let got = 0, steps = 0;
    while (got < n) { const c = (rnd() * n) | 0; steps++; if (!seen[c]) { seen[c] = 1; got++; } }
    sum += steps;
  }
  const mc = sum / TRIALS, theory = fnum(expFormula(n));
  log(approx(mc, theory, 0.05), `Monte Carlo (n=10, 4×10^5 trials): mean T = ${mc.toFixed(3)} vs n·H_n = ${theory.toFixed(3)}`);
}

// 1d. the canonical sizes, exact then rounded — the numbers the page prints.
{
  const lines = [];
  for (const n of [6, 52, 100]) {
    const e = expFormula(n);
    lines.push(`n=${n}: E[T]=${fnum(e).toFixed(2)}`);
  }
  // a standard die: 6·H_6 = 6·(49/20) = 14.7 exactly
  const die = expFormula(6);
  log(feq(die, Frac(147, 10)), `a fair die: E[T] = 6·H_6 = 147/10 = 14.7 rolls exactly`);
  log(true, `   ${lines.join(", ")}`);
}

// ===========================================================================
// PART 2 — THE LAST COUPON DOMINATES
// ===========================================================================
console.log("\n  Part 2 — the last coupon dominates\n");

// The phase waits are n/n, n/(n−1), …, n/1. The FIRST coupon costs 1 draw on
// average; the LAST single coupon costs n draws on average — the largest term in
// the sum by far. So the agony is real and it is the tail.
{
  const n = 100;
  const firstPhase = fnum(Frac(n, n));     // n/(n−0) = 1
  const lastPhase = fnum(Frac(n, 1));      // n/(n−(n−1)) = n
  const total = fnum(expFormula(n));
  log(approx(firstPhase, 1, 1e-12), `first coupon: expected wait = 1 draw (you can't miss)`);
  log(approx(lastPhase, n, 1e-12), `last coupon alone: expected wait = n = ${n} draws`);
  // the single last coupon is ~1/5 of the whole collection time at n=100
  const frac = lastPhase / total;
  log(frac > 0.19 && frac < 0.21, `that one last coupon is ${(100 * frac).toFixed(1)}% of the whole ${total.toFixed(1)}-draw expectation`);
  // and the last TEN coupons (k = n−9 … n) cost more than the first ninety:
  let lastTen = Frac(0); for (let j = 1; j <= 10; j++) lastTen = fadd(lastTen, Frac(n, j));
  const firstNinety = fsub(expFormula(n), lastTen);
  log(fnum(lastTen) > fnum(firstNinety), `the last 10 coupons (${fnum(lastTen).toFixed(1)} draws) cost more than the first 90 (${fnum(firstNinety).toFixed(1)})`);
}

// ===========================================================================
// PART 3 — THE VARIANCE  Var[T] = n²·Σ1/k² − n·H_n
// ===========================================================================
console.log("\n  Part 3 — the variance\n");

// (A) closed form. The phase waits are INDEPENDENT geometrics, so variances add.
//     Phase j (j coupons remaining) is Geometric(p=j/n) with variance (1−p)/p².
//     Σ_{j=1}^{n} (1−j/n)/(j/n)² = n²·Σ 1/j² − n·Σ 1/j = n²·Σ1/k² − n·H_n.
function varFormula(n) {
  let s2 = Frac(0), H = Frac(0);
  for (let k = 1; k <= n; k++) { s2 = fadd(s2, Frac(1, k * k)); H = fadd(H, Frac(1, k)); }
  return fsub(fmul(Frac(n * n), s2), fmul(Frac(n), H));   // n²Σ1/k² − n·H_n
}
// (B) sum of the per-phase geometric variances directly (no algebraic collapse).
function varPhases(n) {
  let v = Frac(0);
  for (let j = 1; j <= n; j++) { const p = Frac(j, n); const q = fsub(Frac(1), p); v = fadd(v, fmul(q, Frac(p.d * p.d, p.n * p.n))); }
  return v;
}
{
  let allOK = true;
  for (let n = 1; n <= 10; n++) if (!feq(varFormula(n), varPhases(n))) allOK = false;
  log(allOK, `Var[T] = n²·Σ1/k² − n·H_n exactly, all n≤10 (collapsed form = sum of phase variances)`);
  // asymptotically Var[T] → n²·π²/6 (since Σ1/k² → π²/6), so the spread is ~n.
  const n = 100000;
  let s2 = 0; for (let k = 1; k <= n; k++) s2 += 1 / (k * k);
  const v = n * n * s2 - n * (Math.log(n) + 0.5772156649);
  const sd = Math.sqrt(v);
  log(approx(s2, Math.PI * Math.PI / 6, 1e-4), `Σ1/k² → π²/6 = ${(Math.PI * Math.PI / 6).toFixed(6)} (at n=10^5, ${s2.toFixed(6)})`);
  log(approx(sd / n, Math.PI / Math.sqrt(6), 1e-3), `so the standard deviation ≈ n·π/√6 ≈ ${(n * Math.PI / Math.sqrt(6)).toExponential(3)} — spread grows only like n, not n·ln n`);
}

// (C) Monte Carlo variance check.
{
  const rnd = mulberry32(0xC0FFEE);
  const n = 20, TRIALS = 300000;
  let s = 0, s2 = 0;
  for (let t = 0; t < TRIALS; t++) {
    const seen = new Uint8Array(n); let got = 0, steps = 0;
    while (got < n) { const c = (rnd() * n) | 0; steps++; if (!seen[c]) { seen[c] = 1; got++; } }
    s += steps; s2 += steps * steps;
  }
  const mcVar = s2 / TRIALS - (s / TRIALS) ** 2;
  const theory = fnum(varFormula(n));
  log(approx(mcVar / theory, 1, 0.03), `Monte Carlo Var (n=20, 3×10^5 trials): ${mcVar.toFixed(1)} vs formula ${theory.toFixed(1)}`);
}

// ===========================================================================
// PART 4 — THE ASYMPTOTIC LAW  E[T] = n ln n + γn + 1/2 + o(1)
// ===========================================================================
console.log("\n  Part 4 — the asymptotic size and the Gumbel limit law\n");

// 4a. E[T] = n·H_n = n(ln n + γ + 1/(2n) − …) = n ln n + γn + 1/2 + o(1).
{
  const GAMMA = 0.5772156649015329;
  let okAll = true, lines = [];
  for (const n of [100, 1000, 100000]) {
    let H = 0; for (let k = 1; k <= n; k++) H += 1 / k;
    const exact = n * H;
    const approx2 = n * Math.log(n) + GAMMA * n + 0.5;
    const relErr = Math.abs(exact - approx2) / exact;
    if (relErr > 1e-3) okAll = false;
    if (n === 1000 || n === 100000) lines.push(`n=${n}: n·H_n=${exact.toFixed(1)}, n ln n+γn+½=${approx2.toFixed(1)}`);
  }
  log(okAll, `E[T] = n ln n + γn + 1/2 + o(1) (relative error <10⁻³ by n=100)`);
  log(true, `   ${lines.join(" | ")}`);
}

// 4b. the GUMBEL limit (Erdős–Rényi, 1961): P(T ≤ n ln n + c·n) → exp(−exp(−c)).
//     Monte Carlo the standardised collection time at large n against the
//     double-exponential CDF, for several c. This is the deep fact: the
//     fluctuations of T, rescaled, converge to the Gumbel distribution.
{
  const rnd = mulberry32(0x5EED);
  const n = 4000, TRIALS = 60000;
  const samples = new Float64Array(TRIALS);
  for (let t = 0; t < TRIALS; t++) {
    const seen = new Uint8Array(n); let got = 0, steps = 0;
    while (got < n) { const c = (rnd() * n) | 0; steps++; if (!seen[c]) { seen[c] = 1; got++; } }
    samples[t] = (steps - n * Math.log(n)) / n;        // standardised: (T − n ln n)/n
  }
  let okAll = true, lines = [];
  for (const c of [-1, 0, 1, 2]) {
    let below = 0; for (let t = 0; t < TRIALS; t++) if (samples[t] <= c) below++;
    const emp = below / TRIALS, gumbel = Math.exp(-Math.exp(-c));
    if (Math.abs(emp - gumbel) > 0.015) okAll = false;
    lines.push(`c=${c}: ${emp.toFixed(3)} vs ${gumbel.toFixed(3)}`);
  }
  log(okAll, `P((T−n ln n)/n ≤ c) → exp(−exp(−c)) [Gumbel], n=4000: ${lines.join(", ")}`);
  // the median: exp(−exp(−c))=1/2 ⇒ c = −ln(ln 2) ≈ 0.3665, so median ≈ n ln n + 0.3665 n
  const cMed = -Math.log(Math.log(2));
  const sorted = Array.from(samples).sort((a, b) => a - b);
  const empMed = sorted[(TRIALS / 2) | 0];
  log(approx(empMed, cMed, 0.03), `median of (T−n ln n)/n ≈ −ln(ln 2) = ${cMed.toFixed(4)} (empirical ${empMed.toFixed(4)})`);
}

// ===========================================================================
// PART 5 — THE BIRTHDAY MIRROR & THE PARTIAL-COLLECTION CURVE
// ===========================================================================
console.log("\n  Part 5 — partial collection (how the set fills up)\n");

// 5a. Expected number of DISTINCT coupons after exactly m draws:
//     E[distinct] = n(1 − (1−1/n)^m). Closed form vs Monte Carlo.
{
  function distinctFormula(n, m) { return n * (1 - Math.pow(1 - 1 / n, m)); }
  const rnd = mulberry32(0xBEEF);
  const n = 50, TRIALS = 200000;
  let okAll = true, lines = [];
  for (const m of [25, 50, 100, 200]) {
    let sum = 0;
    for (let t = 0; t < TRIALS; t++) {
      const seen = new Uint8Array(n); let got = 0;
      for (let d = 0; d < m; d++) { const c = (rnd() * n) | 0; if (!seen[c]) { seen[c] = 1; got++; } }
      sum += got;
    }
    const mc = sum / TRIALS, f = distinctFormula(n, m);
    if (Math.abs(mc - f) > 0.1) okAll = false;
    if (m === 50 || m === 100) lines.push(`m=${m}: ${mc.toFixed(2)} vs ${f.toFixed(2)}`);
  }
  log(okAll, `E[distinct after m draws] = n(1−(1−1/n)^m) (n=50): ${lines.join(", ")}`);
  // For even n, the FIRST half goes from 0 to n/2 distinct coupons:
  // E[first half] = n·(H_n − H_{n/2}); E[first half]/n tends to ln 2.
  // The SECOND half goes from n/2 to n and costs n·H_{n/2} on average.
  // Check the state ranges directly against the two harmonic formulas.
  const n2 = 1000;
  let Hn = 0, Hh = 0; for (let k = 1; k <= n2; k++) { Hn += 1 / k; if (k <= n2 / 2) Hh += 1 / k; }
  const tHalf = n2 * (Hn - Hh);
  const tRest = n2 * Hh;
  let firstPhases = 0, lastPhases = 0;
  for (let k = 0; k < n2; k++) {
    if (k < n2 / 2) firstPhases += n2 / (n2 - k);
    else lastPhases += n2 / (n2 - k);
  }
  log(approx(tHalf, firstPhases, 1e-8) && approx(tRest, lastPhases, 1e-8)
    && approx(tHalf / n2, Math.log(2), 0.01),
    `first half (0 to n/2 distinct): n·(H_n−H_{n/2}) = ${tHalf.toFixed(3)} expected draws; second half (n/2 to n): n·H_{n/2} = ${tRest.toFixed(3)} at n=${n2}; first-half cost/n tends to ln 2`);
}

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