// verify.mjs — reservoir sampling, every claim on the page recomputed offline.
//
// Run:  node research/reservoir-sampling/verify.mjs
//
// What it proves (and how it is checked):
//   1. Algorithm R (k=1) is UNIFORM. Both ways:
//        (a) exact — the telescoping product P(item j survives) = 1/n for every j;
//        (b) empirical — a seeded Monte-Carlo run whose per-position tallies pass a
//            chi-square goodness-of-fit test against the uniform 1/n.
//   2. Algorithm R (general k) leaves every item in the reservoir with prob k/n.
//   3. The tempting WRONG rule (replace with a FIXED probability p at every step)
//      is NOT uniform: the last item wins with probability exactly p, and the
//      win-distribution is geometric toward the end. Checked exact vs. simulated.
//   4. Weighted reservoir sampling (Efraimidis-Spirakis A-Res), k=1: item i is the
//      survivor with probability EXACTLY w_i / sum(w). Checked three ways — the closed
//      integral, the exact formula, and a seeded simulation of the key rule
//      key_i = u_i^(1/w_i), keep the largest key.
//
// The page states only what turns green here. Nothing is asserted that isn't recomputed.
'use strict';

// ── seeded PRNG (mulberry32), identical to the one the page ships ─────────────
function mulberry32(seed) {
  let a = seed >>> 0;
  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;
  };
}

let PASS = 0, FAIL = 0;
function ok(name, cond, detail) {
  if (cond) { PASS++; console.log(`  ok   ${name}${detail ? '  — ' + detail : ''}`); }
  else { FAIL++; console.log(`  FAIL ${name}${detail ? '  — ' + detail : ''}`); }
}
function approx(a, b, tol) { return Math.abs(a - b) <= tol; }

// ═════════════════════════════════════════════════════════════════════════════
// 1a. EXACT: the telescoping product. Item j (1-indexed) is the final survivor iff
//     it enters the slot at step j (prob 1/j) and is never evicted afterwards
//     (each later step i>j keeps it with prob (i-1)/i). The product telescopes:
//       (1/j) * prod_{i=j+1..n} (i-1)/i  =  (1/j)*(j/(j+1))*((j+1)/(j+2))*...*((n-1)/n)
//                                        =  (1/j)*(j/n)  =  1/n.
// We compute the product in exact rationals (BigInt num/den) so there is zero
// floating-point slack: it must equal 1/n on the nose.
console.log('\n[1a] Algorithm R (k=1): exact survival probability = 1/n (rational)');
function bgcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
function reduce(n, d) { const g = bgcd(n, d) || 1n; return [n / g, d / g]; }
for (const n of [1, 2, 3, 7, 20, 100]) {
  let allEqual = true;
  for (let j = 1; j <= n; j++) {
    // enter-slot probability: item 1 enters with certainty (1/1); item j with 1/j.
    let num = 1n, den = BigInt(j);
    for (let i = j + 1; i <= n; i++) { num *= BigInt(i - 1); den *= BigInt(i); }
    const [rn, rd] = reduce(num, den);
    // must equal 1/n exactly:  rn/rd == 1/n  <=>  rn*n == rd
    if (!(rn * BigInt(n) === rd)) { allEqual = false; break; }
  }
  ok(`n=${n}: every position has exact probability 1/${n}`, allEqual);
}

// ═════════════════════════════════════════════════════════════════════════════
// 1b. EMPIRICAL: run Algorithm R (k=1) many times, tally survivors by position,
//     and run a chi-square goodness-of-fit test against uniform. The page shows
//     this histogram flattening; here we assert it is statistically uniform.
console.log('\n[1b] Algorithm R (k=1): Monte-Carlo tallies pass chi-square uniform test');
function reservoirK1(n, rnd) {
  let keep = 0;                       // 0-indexed position currently held
  for (let i = 1; i < n; i++) {       // item at index i arrives; it is the (i+1)-th item
    if (rnd() < 1 / (i + 1)) keep = i; // replace with probability 1/(i+1)
  }
  return keep;
}
{
  const n = 20, trials = 200000, rnd = mulberry32(12345);
  const tally = new Array(n).fill(0);
  for (let t = 0; t < trials; t++) tally[reservoirK1(n, rnd)]++;
  const expected = trials / n;
  let chi2 = 0;
  for (let i = 0; i < n; i++) { const d = tally[i] - expected; chi2 += d * d / expected; }
  // df = 19; chi-square 0.995 critical ~ 38.58. We assert we do NOT reject uniformity.
  const crit995 = 38.582;
  ok(`n=${n}, ${trials} trials: chi2=${chi2.toFixed(2)} < ${crit995} (df=19)`, chi2 < crit995);
  const maxDev = Math.max(...tally.map(c => Math.abs(c / trials - 1 / n)));
  ok(`max deviation from 1/${n} is small`, maxDev < 0.01, `maxDev=${maxDev.toFixed(4)}`);
}

// ═════════════════════════════════════════════════════════════════════════════
// 2. General k: after the stream, each of the n items is in the reservoir with
//    probability k/n. Empirical marginal check.
console.log('\n[2] Algorithm R (general k): each item retained with prob k/n');
function reservoirK(n, k, rnd) {
  const res = [];
  for (let i = 0; i < n; i++) {
    if (i < k) { res.push(i); }
    else {
      // keep item i with probability k/(i+1); if kept, it replaces a uniform slot.
      if (rnd() < k / (i + 1)) res[Math.floor(rnd() * k)] = i;
    }
  }
  return res;
}
{
  const n = 30, k = 5, trials = 200000, rnd = mulberry32(777);
  const tally = new Array(n).fill(0);
  for (let t = 0; t < trials; t++) for (const idx of reservoirK(n, k, rnd)) tally[idx]++;
  const p = k / n;
  const maxDev = Math.max(...tally.map(c => Math.abs(c / trials - p)));
  ok(`n=${n}, k=${k}: every item retained ~${p.toFixed(3)} of the time`, maxDev < 0.01,
     `maxDev=${maxDev.toFixed(4)}`);
  // reservoir always holds exactly k distinct items
  const sample = reservoirK(n, k, mulberry32(999));
  ok(`reservoir holds exactly k=${k} distinct items`,
     sample.length === k && new Set(sample).size === k);
}

// ═════════════════════════════════════════════════════════════════════════════
// 3. The WRONG rule: replace with a FIXED probability p every step. This feels
//    symmetric but it is not uniform — it is geometric toward the end. Exactly:
//      P(item n wins) = p                         (the last item, if it replaces, wins)
//      P(item n-1 wins) = p(1-p), ...             geometric back from the end
//      P(item 1 wins) = (1-p)^(n-1)               (survives if nobody ever replaces)
//    (Here "replace" for the first item means it is simply the initial holder.)
console.log('\n[3] Fixed-probability rule is NOT uniform (geometric toward the end)');
function fixedP(n, p, rnd) {
  let keep = 0;
  for (let i = 1; i < n; i++) if (rnd() < p) keep = i;
  return keep;
}
{
  const n = 8, p = 0.5, trials = 400000, rnd = mulberry32(2024);
  const tally = new Array(n).fill(0);
  for (let t = 0; t < trials; t++) tally[fixedP(n, p, rnd)]++;
  // exact: last item index n-1 -> p; index i (1..n-2) -> p*(1-p)^(n-1-i); index 0 -> (1-p)^(n-1)
  const exact = new Array(n);
  exact[n - 1] = p;
  for (let i = n - 2; i >= 1; i--) exact[i] = p * Math.pow(1 - p, n - 1 - i);
  exact[0] = Math.pow(1 - p, n - 1);
  const sum = exact.reduce((a, b) => a + b, 0);
  ok('exact win-probabilities sum to 1', approx(sum, 1, 1e-12), `sum=${sum}`);
  let maxErr = 0;
  for (let i = 0; i < n; i++) maxErr = Math.max(maxErr, Math.abs(tally[i] / trials - exact[i]));
  ok('simulation matches the exact geometric distribution', maxErr < 0.01, `maxErr=${maxErr.toFixed(4)}`);
  // and it is emphatically NOT uniform: last item is far above 1/n
  ok(`last item wins with prob p=${p}, vastly more than 1/${n}=${(1 / n).toFixed(3)}`,
     approx(tally[n - 1] / trials, p, 0.01));
}

// ═════════════════════════════════════════════════════════════════════════════
// 4. Weighted reservoir (Efraimidis-Spirakis A-Res), k=1: assign each item a key
//    key_i = u_i^(1/w_i), u_i ~ Uniform(0,1), keep the largest key. Claim:
//        P(item i is the survivor) = w_i / sum_j w_j   EXACTLY.
//    Proof shown on the page (and re-derived here): key_i has CDF F_i(x)=x^{w_i} on
//    [0,1], so P(i is the max) = ∫_0^1 w_i x^{w_i-1} * prod_{j≠i} x^{w_j} dx
//                              = ∫_0^1 w_i x^{(Σw)-1} dx = w_i / Σw.
console.log('\n[4] Weighted A-Res (k=1): P(survivor=i) = w_i / Σw, exactly');
function aResK1(weights, rnd) {
  let best = -Infinity, keep = 0;
  for (let i = 0; i < weights.length; i++) {
    const u = rnd();
    const key = Math.pow(u, 1 / weights[i]);
    if (key > best) { best = key; keep = i; }
  }
  return keep;
}
{
  const weights = [1, 2, 3, 4]; // Σw = 10
  const W = weights.reduce((a, b) => a + b, 0);
  const trials = 500000, rnd = mulberry32(31415);
  const tally = new Array(weights.length).fill(0);
  for (let t = 0; t < trials; t++) tally[aResK1(weights, rnd)]++;
  let maxErr = 0;
  for (let i = 0; i < weights.length; i++) {
    const want = weights[i] / W;
    maxErr = Math.max(maxErr, Math.abs(tally[i] / trials - want));
  }
  ok(`weights ${JSON.stringify(weights)} -> win-rates match w_i/Σw`, maxErr < 0.01,
     `maxErr=${maxErr.toFixed(4)}`);

  // closed-form integral check: ∫_0^1 w_i x^{W-1} dx = w_i/W (numerically, fine grid)
  let integralMaxErr = 0;
  for (let i = 0; i < weights.length; i++) {
    const wi = weights[i]; const N = 2000000; let acc = 0;
    for (let s = 0; s < N; s++) { const x = (s + 0.5) / N; acc += wi * Math.pow(x, W - 1); }
    acc /= N;
    integralMaxErr = Math.max(integralMaxErr, Math.abs(acc - wi / W));
  }
  ok('closed integral ∫ w_i x^{Σw-1} dx equals w_i/Σw', integralMaxErr < 1e-4,
     `maxErr=${integralMaxErr.toExponential(2)}`);

  // equal weights degenerate to plain uniform reservoir (sanity)
  const eq = [1, 1, 1, 1, 1], rnd2 = mulberry32(2718), tally2 = new Array(5).fill(0);
  for (let t = 0; t < 300000; t++) tally2[aResK1(eq, rnd2)]++;
  const dev = Math.max(...tally2.map(c => Math.abs(c / 300000 - 0.2)));
  ok('equal weights reduce to uniform (each 1/5)', dev < 0.01, `maxDev=${dev.toFixed(4)}`);
}

// ═════════════════════════════════════════════════════════════════════════════
// 5. Cross-check: the O(1)-memory guarantee. Algorithm R never holds more than k
//    items regardless of stream length. (Structural, not statistical.)
console.log('\n[5] Memory is O(k) regardless of n');
{
  let maxHeld = 0;
  const n = 100000, k = 7, rnd = mulberry32(5);
  const res = [];
  for (let i = 0; i < n; i++) {
    if (i < k) res.push(i);
    else if (rnd() < k / (i + 1)) res[Math.floor(rnd() * k)] = i;
    maxHeld = Math.max(maxHeld, res.length);
  }
  ok(`over a stream of ${n.toLocaleString('en-US')} items, never held more than k=${k}`, maxHeld === k,
     `maxHeld=${maxHeld}`);
}

console.log(`\n${FAIL === 0 ? 'ALL GREEN' : 'RED'} — ${PASS} passed, ${FAIL} failed\n`);
process.exit(FAIL === 0 ? 0 : 1);
