#!/usr/bin/env node
// The inspection paradox — length-biased sampling in time, verified.
//
// One identity underlies the whole page: when you sample intervals in proportion
// to their own size, the mean you get is not E[X] but
//
//     E[X_sampled] = E[X²] / E[X] = μ + σ²/μ = μ·(1 + CV²)             (Cox, Renewal Theory)
//
// and the time you wait until the next renewal (the forward recurrence) is half of
// that spread interval:
//
//     E[wait] = E[X²] / (2·E[X]) = E[X_sampled] / 2.
//
// This file re-derives those numbers two independent ways for four gap
// distributions — a closed form from the raw moments, and a genuine timeline
// simulation that drops uniformly-random arrivals onto a long strip of renewals
// and reads off the interval each one lands in (no length-weighting assumed; the
// weighting has to *emerge*). Then it checks the two everyday consequences the
// page turns on: the Poisson bus (you land in a 2×-mean gap and wait a full mean,
// not half) and the class-size paradox (the class a random student sits in is far
// bigger than the average class). Every displayed number on the page is one of
// these. Seeded; reproducible; deterministic pass/fail.

// ── seeded PRNG (mulberry32) — identical to the one in the page ───────────────
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;
  };
}

// ── gap distributions, all with a tunable mean; sampler + exact first two moments ──
function expDist(mean) {
  return {
    name: `exponential(mean ${mean}) — a Poisson bus`,
    sample: (r) => -mean * Math.log(1 - r()),
    m1: mean,
    m2: 2 * mean * mean, // E[X²] = 2μ² for exponential  (Var = μ², CV = 1)
  };
}
function constDist(c) {
  return {
    name: `constant(${c}) — a perfectly regular clock`,
    sample: (_r) => c,
    m1: c,
    m2: c * c, // Var = 0, CV = 0
  };
}
function erlangDist(k, scale) {
  // sum of k exponentials, each mean=scale. mean = k·scale, Var = k·scale², CV = 1/√k.
  const mean = k * scale;
  return {
    name: `Erlang(k=${k}, mean ${mean}) — a fairly steady service, CV=${(1 / Math.sqrt(k)).toFixed(3)}`,
    sample: (r) => { let s = 0; for (let i = 0; i < k; i++) s += -scale * Math.log(1 - r()); return s; },
    m1: mean,
    m2: k * (k + 1) * scale * scale, // E[X²] for Erlang(k,scale)
  };
}
function twoPoint(pShort, short, long, prob) {
  // gaps are `short` w.p. `prob`, else `long`. A bursty timetable: many quick
  // arrivals then a rare long silence. prob·short + (1-prob)·long = mean.
  const p = prob, q = 1 - prob;
  return {
    name: `two-point {${short} w.p. ${p}, ${long} w.p. ${q.toFixed(2)}} — a bursty timetable`,
    sample: (r) => (r() < p ? short : long),
    m1: p * short + q * long,
    m2: p * short * short + q * long * long,
  };
}

// ── the genuine timeline simulation ──────────────────────────────────────────
// Build a long strip of consecutive gaps; drop K uniformly-random arrival instants
// on it; for each, find the interval it fell inside and record that interval's
// LENGTH and the WAIT until the next renewal. Nothing here weights by length — the
// bias has to appear on its own from where uniform darts happen to land.
function simulate(dist, seed, nGaps, nArrivals) {
  const r = mulberry32(seed);
  const bound = new Float64Array(nGaps + 1);
  const gap = new Float64Array(nGaps);
  let t = 0;
  for (let i = 0; i < nGaps; i++) { const g = dist.sample(r); gap[i] = g; t += g; bound[i + 1] = t; }
  const total = t;
  // uniformly-random arrival instants, sorted, then a single merge sweep
  const arr = new Float64Array(nArrivals);
  for (let j = 0; j < nArrivals; j++) arr[j] = r() * total;
  arr.sort();
  let sumLen = 0, sumWait = 0, sumAge = 0, idx = 0;
  for (let j = 0; j < nArrivals; j++) {
    const u = arr[j];
    while (bound[idx + 1] <= u && idx < nGaps - 1) idx++;
    sumLen += gap[idx];
    sumWait += bound[idx + 1] - u;   // forward recurrence (time to next renewal)
    sumAge += u - bound[idx];        // backward recurrence (age of current interval)
  }
  return { simLen: sumLen / nArrivals, simWait: sumWait / nArrivals, simAge: sumAge / nArrivals };
}

// ── harness ──────────────────────────────────────────────────────────────────
let passed = 0, failed = 0;
const notes = [];
function ok(name, cond, detail) {
  if (cond) { passed++; console.log(`  ✓ ${name}${detail ? '  — ' + detail : ''}`); }
  else { failed++; console.log(`  ✗ ${name}${detail ? '  — ' + detail : ''}`); }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const rel = (a, b, frac) => Math.abs(a - b) <= frac * Math.abs(b) + 1e-9;

console.log('\nINSPECTION PARADOX — length-biased sampling in time\n' + '─'.repeat(64));

const MEAN = 10;
const dists = [
  constDist(MEAN),
  erlangDist(4, 2.5),                 // CV = 0.5
  expDist(MEAN),                      // CV = 1  (the Poisson bus)
  twoPoint(0.9, 2, 82, 0.9),          // mean 10, CV ≈ 2.4  (bursty)
];

console.log('\n[A] Closed form  E[L]=E[X²]/E[X]  vs a genuine uniform-arrival timeline sim');
console.log('     (no length-weighting is assumed anywhere; it has to emerge)\n');
for (const d of dists) {
  const eL = d.m2 / d.m1;              // spread interval  = μ + σ²/μ
  const eW = d.m2 / (2 * d.m1);        // forward recurrence = E[L]/2
  const cv2 = d.m2 / (d.m1 * d.m1) - 1;
  const sim = simulate(d, 0x1a2b3c, 200000, 3000000);
  console.log(`  ${d.name}`);
  ok(`    E[L] closed=${eL.toFixed(3)}  sim=${sim.simLen.toFixed(3)}`, rel(sim.simLen, eL, 0.02));
  ok(`    E[wait] closed=${eW.toFixed(3)}  sim=${sim.simWait.toFixed(3)}`, rel(sim.simWait, eW, 0.02));
  ok(`    E[age]≈E[wait] (symmetry)  sim age=${sim.simAge.toFixed(3)}`, rel(sim.simAge, eW, 0.03));
  ok(`    identity  E[L] = μ(1+CV²) = ${MEAN}·(1+${cv2.toFixed(3)}) = ${(MEAN * (1 + cv2)).toFixed(3)}`,
     near(eL, MEAN * (1 + cv2), 1e-9));
  ok(`    the spread interval is never shorter than a typical one (E[L] ≥ μ)`, eL >= d.m1 - 1e-9);
}

console.log('\n[B] The two headline everyday numbers the page states\n');

// The Poisson bus: mean gap 10 min → you land in a 20-min gap and wait 10, not 5.
{
  const d = expDist(10);
  const eL = d.m2 / d.m1, eW = d.m2 / (2 * d.m1);
  ok('Poisson bus, mean gap 10 min: the gap you land in averages 20 min (2× the mean)', near(eL, 20, 1e-9), `E[L]=${eL}`);
  ok('Poisson bus: your average wait is a FULL 10 min, not the intuitive 5', near(eW, 10, 1e-9), `E[wait]=${eW}`);
  // memorylessness: no matter how long since the last bus, the wait is still exp(mean 10)
  const r = mulberry32(7);
  let s = 0, n = 0;
  for (let i = 0; i < 4000000; i++) {
    const g = -10 * Math.log(1 - r());
    if (g > 15) { s += (g - 15); n++; }   // among gaps already ≥15 min old, remaining wait
  }
  ok('memorylessness: even 15 min in with no bus, the expected further wait is still ~10 min',
     rel(s / n, 10, 0.02), `mean residual=${(s / n).toFixed(3)}`);
}

// The regular clock: constant gaps → land in a mean gap, wait exactly half. No paradox.
{
  const d = constDist(10);
  ok('perfectly regular clock: you land in a mean-length gap (E[L]=μ), wait exactly μ/2 = 5',
     near(d.m2 / d.m1, 10, 1e-9) && near(d.m2 / (2 * d.m1), 5, 1e-9));
}

console.log('\n[C] The class-size paradox — the same identity, sampled by student not by class');
console.log('     (illustrative college; numbers are a labelled model, the effect is real)\n');
{
  // classes: (size, howManyClassesOfThatSize)
  const classes = [[10, 60], [30, 30], [100, 8], [200, 2]];
  let nClasses = 0, seats = 0, seatSq = 0;
  for (const [size, count] of classes) { nClasses += count; seats += size * count; seatSq += size * size * count; }
  const perClass = seats / nClasses;         // what the brochure advertises (mean over classes)
  const perStudent = seatSq / seats;         // what a random student experiences (size-biased)
  const variance = seatSq / nClasses - perClass * perClass;
  const gap = variance / perClass;
  ok(`per-class mean (advertised) = ${perClass.toFixed(1)}`, near(perClass, 27, 1e-9));
  ok(`per-student mean (experienced) = ${perStudent.toFixed(1)}`, near(perStudent, 193000 / 2700, 1e-6));
  ok('per-student = per-class + variance/mean  (the friendship-paradox identity, again)',
     near(perStudent, perClass + gap, 1e-6), `${perClass.toFixed(1)} + ${gap.toFixed(1)} = ${(perClass + gap).toFixed(1)}`);
  ok('the student sits in a bigger class than the college advertises (per-student > per-class)', perStudent > perClass);
  // independent Monte-Carlo: draw a random STUDENT (seat) and read the class size
  const r = mulberry32(99);
  const flat = [];
  for (const [size, count] of classes) for (let c = 0; c < count; c++) flat.push(size);
  const seatArr = [];
  for (const size of flat) for (let s = 0; s < size; s++) seatArr.push(size);
  let acc = 0, K = 2000000;
  for (let i = 0; i < K; i++) acc += seatArr[Math.floor(r() * seatArr.length)];
  ok(`Monte-Carlo random-student class size ≈ per-student closed form`, rel(acc / K, perStudent, 0.01),
     `sim=${(acc / K).toFixed(2)}`);
  notes.push(`class-size: advertised ${perClass.toFixed(0)}, a student's average class ${perStudent.toFixed(1)}`);
}

console.log('\n[D] Pencil-and-paper anchor (no simulation, by hand)\n');
{
  // Two intervals only: lengths 1 and 9, equally likely. Timeline is …1,9,1,9,… so
  // 90% of the LINE is inside 9-length gaps. A uniform dart lands in a 9-gap w.p. 0.9.
  // E[X]=5, E[X²]=(1+81)/2=41, E[L]=41/5=8.2, P(land in the 9)=9/(1+9)=0.9.
  const eX = 5, eX2 = 41, eL = eX2 / eX;
  ok('by hand: gaps {1,9} equally likely → E[X]=5 but E[L]=41/5=8.2', near(eL, 8.2, 1e-9));
  ok('by hand: a uniform arrival lands in the 9-gap 90% of the time (9/10 of the timeline)', near(9 / 10, 0.9, 1e-12));
}

console.log('\n' + '─'.repeat(64));
if (notes.length) { console.log('notes:'); for (const n of notes) console.log('  · ' + n); }
console.log(`\n${passed}/${passed + failed} pass${failed ? `  (${failed} FAILED)` : ''}\n`);
process.exit(failed ? 1 : 0);
