// The 100 Prisoners Problem — correctness-first verification.
//
// Claim (the headline): 100 prisoners, boxes 1..100 each holding a distinct slip
// 1..100 in a random arrangement. Each prisoner may open at most 50 boxes and must
// find his own number. Under the naive strategy (open any 50) the whole room
// succeeds with probability (1/2)^100 ≈ 8e-31. Under the LOOP strategy (start at the
// box with your own number, then open the box numbered by the slip you find, and
// follow that chain) the whole room succeeds with probability ≈ 0.31183 — and in the
// large-room limit → 1 − ln 2 ≈ 0.30685.
//
// We prove every number THREE independent ways and assert they agree:
//   (A) the exact closed form  P(success) = 1 − (H_{2k} − H_k)  via BigInt rationals
//       (no floating point: a permutation of 2k has a cycle longer than k with
//        probability exactly Σ_{L=k+1}^{2k} 1/L, since at most one such cycle exists),
//   (B) brute-force enumeration of ALL (2k)! permutations for small 2k, counting the
//       fraction whose longest cycle ≤ k (trusts nothing about the formula),
//   (C) a Monte-Carlo simulation that actually plays the game — builds a random
//       arrangement, runs the loop strategy box-by-box for every prisoner with the
//       50-open cap, and tallies whole-room success — using the SAME sampler/step
//       loop the page ships, so the page's live number is this number.
//
// Run:  node research/hundred-prisoners/verify.mjs
// Exit code 0 and "ALL CHECKS PASS" iff every cross-check holds.

let pass = 0, fail = 0;
const checks = [];
function check(name, cond, detail = '') {
  if (cond) { pass++; checks.push(`  ✓ ${name}${detail ? ' — ' + detail : ''}`); }
  else { fail++; checks.push(`  ✗ FAIL: ${name}${detail ? ' — ' + detail : ''}`); }
}

// ───────────────────────────────────────────────────────────────────────────
// Exact rational arithmetic over BigInt (no floats in the closed form).
// ───────────────────────────────────────────────────────────────────────────
function gcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
class Q {
  constructor(n, d = 1n) {
    if (d < 0n) { n = -n; d = -d; }
    const g = gcd(n, d) || 1n;
    this.n = n / g; this.d = d / g;
  }
  add(o) { return new Q(this.n * o.d + o.n * this.d, this.d * o.d); }
  sub(o) { return new Q(this.n * o.d - o.n * this.d, this.d * o.d); }
  toNumber() { return Number(this.n) / Number(this.d); }
  toString() { return `${this.n}/${this.d}`; }
}
// Harmonic number H_m as an exact rational.
function H(m) {
  let s = new Q(0n, 1n);
  for (let i = 1; i <= m; i++) s = s.add(new Q(1n, BigInt(i)));
  return s;
}

// ───────────────────────────────────────────────────────────────────────────
// (A) Exact closed form: success probability for 2k boxes, cap k.
//     P = 1 − (H_{2k} − H_k).
// ───────────────────────────────────────────────────────────────────────────
function exactSuccess(twoK) {
  if (twoK % 2 !== 0) throw new Error('use an even number of boxes');
  const k = twoK / 2;
  const ONE = new Q(1n, 1n);
  return ONE.sub(H(twoK).sub(H(k))); // exact rational
}

// ───────────────────────────────────────────────────────────────────────────
// (B) Brute force: enumerate every permutation of n = 2k boxes, count those whose
//     longest cycle ≤ k. Done by Heap's algorithm; permutation π means box i holds
//     slip π[i]. Cycle lengths of π drive the loop-strategy outcome exactly.
// ───────────────────────────────────────────────────────────────────────────
function longestCycle(perm) {
  const n = perm.length, seen = new Array(n).fill(false);
  let longest = 0;
  for (let i = 0; i < n; i++) {
    if (seen[i]) continue;
    let len = 0, j = i;
    while (!seen[j]) { seen[j] = true; j = perm[j]; len++; }
    if (len > longest) longest = len;
  }
  return longest;
}
function bruteForceSuccessFraction(n) {
  const k = n / 2;
  const a = Array.from({ length: n }, (_, i) => i);
  let total = 0n, good = 0n;
  // Heap's algorithm — every permutation exactly once.
  const c = new Array(n).fill(0);
  const tally = () => { total++; if (longestCycle(a) <= k) good++; };
  tally();
  let i = 0;
  while (i < n) {
    if (c[i] < i) {
      if (i % 2 === 0) { [a[0], a[i]] = [a[i], a[0]]; }
      else { [a[c[i]], a[i]] = [a[i], a[c[i]]]; }
      tally(); c[i]++; i = 0;
    } else { c[i] = 0; i++; }
  }
  return { good, total }; // exact integer counts
}

// ───────────────────────────────────────────────────────────────────────────
// (C) THE GAME, PLAYED. This is the exact sampler/step-loop the page ships.
//     - randomArrangement(n): a uniform random permutation (Fisher–Yates).
//       box[i] = the slip in box i (0-indexed slips/boxes for the engine).
//     - prisonerFinds(box, p, cap): play the loop strategy for prisoner p; return
//       the step on which slip p is found, or -1 if not within `cap` opens.
//     - roomSucceeds(box, cap): every prisoner finds their slip within the cap.
//     These three functions are duplicated verbatim in the page's <script>.
// ───────────────────────────────────────────────────────────────────────────
function makeRNG(seed) { // mulberry32 — deterministic, matches the page
  let s = seed >>> 0;
  return function () {
    s |= 0; s = (s + 0x6D2B79F5) | 0;
    let t = Math.imul(s ^ (s >>> 15), 1 | s);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
function randomArrangement(n, rng) {
  const box = Array.from({ length: n }, (_, i) => i);
  for (let i = n - 1; i > 0; i--) {
    const j = Math.floor(rng() * (i + 1));
    [box[i], box[j]] = [box[j], box[i]];
  }
  return box;
}
function prisonerFinds(box, p, cap) {
  let cur = p; // start at the box bearing your own number
  for (let step = 1; step <= cap; step++) {
    const slip = box[cur];
    if (slip === p) return step;
    cur = slip; // follow the chain
  }
  return -1;
}
function roomSucceeds(box, cap) {
  const n = box.length;
  for (let p = 0; p < n; p++) if (prisonerFinds(box, p, cap) === -1) return false;
  return true;
}
// Naive strategy: each prisoner opens a uniformly random `cap`-subset of boxes.
function roomSucceedsNaive(box, cap, rng) {
  const n = box.length;
  for (let p = 0; p < n; p++) {
    // shuffle the boxes this prisoner inspects; succeed iff slip p among first cap
    let found = false;
    const order = randomArrangement(n, rng); // reuse FY shuffle for the subset order
    for (let s = 0; s < cap; s++) { if (box[order[s]] === p) { found = true; break; } }
    if (!found) return false;
  }
  return true;
}
function monteCarlo(n, cap, trials, seed, naive = false) {
  const rng = makeRNG(seed);
  let wins = 0;
  for (let t = 0; t < trials; t++) {
    const box = randomArrangement(n, rng);
    if (naive ? roomSucceedsNaive(box, cap, rng) : roomSucceeds(box, cap)) wins++;
  }
  return wins / trials;
}

// ───────────────────────────────────────────────────────────────────────────
// RUN THE CROSS-CHECKS
// ───────────────────────────────────────────────────────────────────────────
console.log('THE 100 PRISONERS PROBLEM — verification\n');

// 1. Exact closed form for the headline n=100, k=50.
const p100 = exactSuccess(100);
const p100f = p100.toNumber();
check('exact P(success) for n=100 computed as a rational', p100.d > 1n,
  `= ${p100f.toFixed(10)}`);
check('n=100 success ≈ 0.3118278', Math.abs(p100f - 0.3118278206) < 1e-9,
  p100f.toFixed(10));

// naive room success = (1/2)^100
const naive100 = Math.pow(0.5, 100);
check('naive strategy for n=100 ≈ 7.9e-31', Math.abs(naive100 - 7.888609e-31) < 1e-36,
  naive100.toExponential(4));
check('loop strategy is ~3.95e29× better than naive', p100f / naive100 > 3.9e29,
  `${(p100f / naive100).toExponential(3)}×`);

// 2. Limit 1 − ln 2.
//    For large n the exact rational's numerator/denominator overflow JS Number, so the
//    limit/trend is checked with a float harmonic. (The exact rational form is already
//    cross-validated against brute force at small n above; here we only watch the trend.)
const target = 1 - Math.log(2);
check('1 − ln 2 ≈ 0.3068528', Math.abs(target - 0.3068528194) < 1e-9, target.toFixed(10));
function successFloat(twoK) { // P = 1 − Σ_{L=k+1}^{2k} 1/L, in float
  const k = twoK / 2; let s = 0; for (let L = k + 1; L <= twoK; L++) s += 1 / L; return 1 - s;
}
check('float trend agrees with exact rational at n=100', Math.abs(successFloat(100) - p100f) < 1e-12,
  successFloat(100).toFixed(12));
const p1000 = successFloat(1000);
const p10000 = successFloat(10000);
check('success decreases monotonically toward 1−ln2', p100f > p1000 && p1000 > p10000 && p10000 > target,
  `n=100:${p100f.toFixed(5)} > n=1000:${p1000.toFixed(5)} > n=10000:${p10000.toFixed(5)} > ${target.toFixed(5)}`);
check('n=10000 within 5e-5 of the 1−ln2 limit', Math.abs(p10000 - target) < 5e-5,
  `Δ=${(p10000 - target).toExponential(3)}`);

// 3. Brute force == exact closed form, for every even n up to 10.
for (const n of [2, 4, 6, 8, 10]) {
  const { good, total } = bruteForceSuccessFraction(n);
  const exactQ = exactSuccess(n);
  // exact fraction good/total should equal exactQ as a rational
  const lhs = good * exactQ.d, rhs = exactQ.n * total;
  check(`brute force == closed form, n=${n}`, lhs === rhs,
    `enumerated ${total} perms, ${good} succeed = ${(Number(good) / Number(total)).toFixed(6)} vs ${exactQ.toNumber().toFixed(6)}`);
}

// factorial sanity on the enumeration counts
function fact(m) { let f = 1n; for (let i = 2n; i <= BigInt(m); i++) f *= i; return f; }
for (const n of [4, 6, 8]) {
  const { total } = bruteForceSuccessFraction(n);
  check(`enumeration covered all ${n}! permutations`, total === fact(n), `${total} == ${fact(n)}`);
}

// 4. Monte-Carlo (the shipped game engine) reproduces the closed form.
const mcLoop100 = monteCarlo(100, 50, 200000, 12345);
check('MC loop-play n=100 ≈ exact (200k trials, ±0.005)', Math.abs(mcLoop100 - p100f) < 0.005,
  `MC=${mcLoop100.toFixed(5)} vs exact=${p100f.toFixed(5)}`);

const mcNaive100 = monteCarlo(100, 50, 200000, 999, /* naive */ true);
check('MC naive-play n=100 never wins in 200k trials', mcNaive100 === 0,
  `${(mcNaive100 * 200000)} wins`);

// smaller n where MC can resolve the value tightly and the naive rate is non-trivial
const mcLoop10 = monteCarlo(10, 5, 500000, 777);
const exact10 = exactSuccess(10).toNumber();
check('MC loop-play n=10 ≈ exact (500k trials, ±0.003)', Math.abs(mcLoop10 - exact10) < 0.003,
  `MC=${mcLoop10.toFixed(5)} vs exact=${exact10.toFixed(5)}`);

// 5. The cycle-structure heart: P(a uniform perm of n=2k has a cycle of length L) = 1/L
//    for L > k — verified by brute force for n=6,8 across L = k+1..2k.
function cycleLengthHistogram(n) {
  const a = Array.from({ length: n }, (_, i) => i);
  const counts = new Map(); // longest-cycle-length -> count
  const hasCycleOfLen = new Map(); // L -> count of perms having a cycle of exactly length L
  const c = new Array(n).fill(0);
  const tally = () => {
    const seen = new Array(n).fill(false);
    const lensPresent = new Set();
    for (let i = 0; i < n; i++) {
      if (seen[i]) continue;
      let len = 0, j = i; while (!seen[j]) { seen[j] = true; j = a[j]; len++; }
      lensPresent.add(len);
    }
    for (const L of lensPresent) hasCycleOfLen.set(L, (hasCycleOfLen.get(L) || 0n) + 1n);
  };
  tally();
  let i = 0;
  while (i < n) {
    if (c[i] < i) {
      if (i % 2 === 0) { [a[0], a[i]] = [a[i], a[0]]; }
      else { [a[c[i]], a[i]] = [a[i], a[c[i]]]; }
      tally(); c[i]++; i = 0;
    } else { c[i] = 0; i++; }
  }
  return hasCycleOfLen;
}
for (const n of [6, 8]) {
  const k = n / 2;
  const hist = cycleLengthHistogram(n);
  const nfact = fact(n);
  let allMatch = true, dbg = [];
  for (let L = k + 1; L <= n; L++) {
    const cnt = hist.get(L) || 0n;       // # perms with a cycle of length exactly L
    // expected = n!/L  (these are mutually exclusive for L>k since at most one big cycle)
    const expect = nfact / BigInt(L);
    dbg.push(`L=${L}:${cnt}vs${expect}`);
    if (cnt !== expect) allMatch = false;
  }
  check(`P(cycle of length L) = 1/L for L>k, n=${n}`, allMatch, dbg.join(' '));
}

// 6. Equivalence of the two "success" definitions: whole-room loop success
//    ⟺ longest cycle ≤ k, asserted directly on random draws.
{
  const rng = makeRNG(2024);
  let consistent = true;
  for (let t = 0; t < 20000; t++) {
    const box = randomArrangement(100, rng);
    const byPlay = roomSucceeds(box, 50);
    const byCycle = longestCycle(box) <= 50;
    if (byPlay !== byCycle) { consistent = false; break; }
  }
  check('room-succeeds(play) ⟺ longest-cycle ≤ k on 20k random rooms', consistent);
}

// ───────────────────────────────────────────────────────────────────────────
console.log(checks.join('\n'));
console.log(`\n${pass} passed, ${fail} failed.`);
console.log('\nKey numbers (for the page):');
console.log(`  n=100 loop success   = ${p100.toString()}`);
console.log(`                       = ${p100f.toFixed(12)}`);
console.log(`  naive room success   = (1/2)^100 = ${naive100.toExponential(6)}`);
console.log(`  limit (1 − ln 2)     = ${target.toFixed(12)}`);
console.log(`  H_100 − H_50         = ${H(100).sub(H(50)).toNumber().toFixed(12)}`);
if (fail === 0) console.log('\nALL CHECKS PASS');
else { console.log('\nVERIFICATION FAILED'); process.exit(1); }
