#!/usr/bin/env node
/**
 * verify-survival.mjs — the independent reference for the dial on
 * /strata/the-loop-that-saves-them/, and the proof that it is right.
 *
 *   node research/hundred-prisoners/verify-survival.mjs
 *
 * WHAT THIS EXISTS FOR. The page's dial answers one question: what is the
 * probability that a random permutation of n has no cycle longer than cap? From
 * the page's first day until 2026-08-16 it answered with
 *
 *     1 - (H_n - H_cap)
 *
 * which is the classic hundred-prisoners closed form and is TRUE ONLY FOR
 * cap >= n/2. Below half it double-counts, because below half a permutation can
 * contain two long cycles at once and the sum of 1/L counts that permutation
 * twice. The page's two sliders reach the region where it is false: with cap left
 * at its default 50 and n dragged past 138, the subtraction runs past 1 and the
 * dial rendered a NEGATIVE PROBABILITY, reaching -198.63% at n = 1000 where the
 * true value is 5.7e-29. Its companion figure, (cap/n)^n in linear space, was
 * exactly 0 from n = 372 — the smallest positive double is 2^-1074 — and the
 * improvement factor divided by that zero and printed "∞".
 *
 * THE REPLACEMENT, and why it cannot have the same fault. Permutations with every
 * cycle at most cap have exponential generating function exp(sum_{j<=cap} x^j/j).
 * Reading off the coefficient of x^n gives a recurrence over probabilities:
 *
 *     p_m = (1/m) * sum_{j=1..min(m,cap)} p_{m-j},        p_0 = 1
 *
 * Every term is positive, so nothing cancels, and it is exact for every cap
 * rather than for half of them.
 *
 * THREE METHODS ARE ASSERTED TO AGREE, and the third is the one that makes the
 * other two worth anything, because it shares no machinery with either:
 *
 *   1. the recurrence above, which is what the page now runs;
 *   2. the classic closed form, on the half of the domain where it is valid;
 *   3. BRUTE-FORCE ENUMERATION of all n! permutations for n <= 8, counting cycle
 *      lengths directly. No generating function, no recurrence, no arithmetic
 *      more delicate than an integer count.
 *
 * Plus a fourth anchor at the edge: at cap = 1 the answer is exactly 1/n!, which
 * is checked against a sum of logarithms out to n = 1000, five hundred orders of
 * magnitude past where a double can hold the value at all.
 *
 * AND THE OLD METHOD IS KEPT, deliberately, so that its failure is REPRODUCIBLE
 * RATHER THAN ASSERTED. `harmonicForm` below is the page's original function,
 * byte-for-byte in behaviour. The check does not merely say the new method is
 * right; it says the old one returns a negative number at a named, reachable
 * slider position, and it would go red if that ever stopped being true. A
 * regression test for a bug you have fixed is worth more than a comment about it.
 * (The pattern is borrowed from research/p-value/power.mjs, which keeps the
 * underflowing binomial recurrence for exactly this reason.)
 */

/* ------------------------------------------------------ method 1: the recurrence */

/**
 * log10 P(a random permutation of n has every cycle of length <= cap).
 *
 * Two details are load-bearing and both were found by getting them wrong.
 *
 * THE SUM IS TAKEN DIRECTLY, not as a difference of running prefix sums. A
 * prefix sum turns this into O(n) instead of O(n*cap), and it also subtracts two
 * nearly equal totals: by n = 1000 the running total has converged and the
 * difference that should be 1e-29 is computed from two numbers around 2, which
 * throws away every significant digit and returns exactly zero. The fast version
 * was written first and reported that the true answer did not exist.
 *
 * THE RECURRENCE IS LINEAR AND HOMOGENEOUS, so multiplying every stored value by
 * a constant multiplies the answer by that constant. When the window sinks toward
 * the smallest double the whole of it is scaled by 1e250 and the exponent carried
 * alongside. That is why cap = 1 at n = 1000 returns -2567.6 instead of zero.
 */
export function survivalLog10(n, cap) {
  if (cap >= n) return 0;
  if (cap < 1) return -Infinity;
  const p = new Float64Array(n + 1); p[0] = 1; let off = 0;
  for (let m = 1; m <= n; m++) {
    const top = Math.min(m, cap); let s = 0;
    for (let j = 1; j <= top; j++) s += p[m - j];
    p[m] = s / m;
    if (p[m] > 0 && p[m] < 1e-250) { for (let i = 0; i <= m; i++) p[i] *= 1e250; off -= 250; }
  }
  return p[n] > 0 ? Math.log10(p[n]) + off : -Infinity;
}

export const survival = (n, cap) => Math.pow(10, survivalLog10(n, cap));

/* ------------------------------------- method 2: the closed form, where it holds */

/** The page's original function. Kept so its failure is reproducible, not asserted. */
export function harmonicForm(n, cap) {
  if (cap >= n) return 1;
  let s = 0;
  for (let L = cap + 1; L <= n; L++) s += 1 / L;
  return 1 - s;
}

/* -------------------------------- method 3: enumeration, sharing nothing with them */

/** P(no cycle longer than cap), by generating every permutation of n and looking. */
export function bruteForce(n, cap) {
  const a = [...Array(n).keys()];
  let good = 0, total = 0;
  const seen = new Uint8Array(n);
  const recur = (l) => {
    if (l === n) {
      total++;
      seen.fill(0);
      for (let i = 0; i < n; i++) {
        if (seen[i]) continue;
        let len = 0, c = i;
        while (!seen[c]) { seen[c] = 1; c = a[c]; len++; }
        if (len > cap) return;
      }
      good++; return;
    }
    for (let i = l; i < n; i++) {
      [a[l], a[i]] = [a[i], a[l]]; recur(l + 1); [a[l], a[i]] = [a[i], a[l]];
    }
  };
  recur(0);
  return good / total;
}

/** log10(1/n!), by summing logarithms: the exact answer at cap = 1, at any n. */
const logRecipFactorial = n => { let s = 0; for (let i = 1; i <= n; i++) s -= Math.log10(i); return s; };

/* --------------------------------------------------------------------- the check */

if (import.meta.url === `file://${process.argv[1]}`) {
  let fails = 0;
  const ok = (name, cond, extra = '') => { if (!cond) fails++; console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`); };
  const close = (a, b, tol) => Math.abs(a - b) <= tol;

  console.log('THE SURVIVAL CURVE — three methods, asserted to agree\n');

  console.log('1. the recurrence against BRUTE-FORCE ENUMERATION of every permutation');
  for (const [n, cap] of [[4, 1], [5, 2], [6, 2], [6, 4], [7, 1], [7, 3], [8, 1], [8, 3], [8, 5]]) {
    const a = survival(n, cap), b = bruteForce(n, cap);
    ok(`n=${n} cap=${cap}`, close(a, b, 1e-12 * Math.max(b, 1e-9)), `${a.toExponential(10)} vs ${b.toExponential(10)}`);
  }

  console.log('\n2. the recurrence against the classic closed form, where the closed form is VALID');
  for (const [n, cap] of [[10, 5], [100, 50], [100, 73], [200, 100], [996, 498], [1000, 500], [1000, 999]]) {
    const a = survival(n, cap), b = harmonicForm(n, cap);
    ok(`n=${n} cap=${cap} (cap >= n/2)`, close(a, b, 1e-9), `${a.toFixed(12)} vs ${b.toFixed(12)}`);
  }

  console.log('\n3. cap = 1 must be exactly 1/n!, checked by a sum of logarithms');
  for (const n of [5, 8, 100, 500, 1000]) {
    const a = survivalLog10(n, 1), b = logRecipFactorial(n);
    ok(`n=${n}`, close(a, b, 1e-6), `log10 ${a.toFixed(6)} vs ${b.toFixed(6)}`);
  }

  console.log('\n4. the boundaries');
  ok('cap = n is certain', survivalLog10(7, 7) === 0);
  ok('cap > n is certain', survivalLog10(7, 9) === 0);
  ok('cap = 0 is impossible', survivalLog10(7, 0) === -Infinity);
  ok('n=2 cap=1 is exactly 1/2', close(survival(2, 1), 0.5, 1e-15), String(survival(2, 1)));
  ok('the curve is non-decreasing in cap (n=60)',
    Array.from({ length: 60 }, (_, i) => survivalLog10(60, i + 1)).every((v, i, arr) => i === 0 || v >= arr[i - 1] - 1e-12));

  console.log('\n5. THE OLD METHOD, kept so its failure is reproducible rather than asserted.');
  console.log('   These are the slider positions the page could reach, and did.');
  ok('the closed form first returns a NEGATIVE probability at n=138, cap=50',
    harmonicForm(138, 50) < 0 && harmonicForm(136, 50) >= 0,
    `n=136 ${harmonicForm(136, 50).toFixed(4)}, n=138 ${harmonicForm(138, 50).toFixed(4)}`);
  ok('at the slider maximum it reads -198.63% where the truth is 5.7e-29',
    close(harmonicForm(1000, 50) * 100, -198.63, 0.01) && close(survivalLog10(1000, 50), -28.2405, 1e-3),
    `old ${(harmonicForm(1000, 50) * 100).toFixed(2)}%, true ${survival(1000, 50).toExponential(4)}`);
  ok('the recurrence is positive everywhere the closed form went negative',
    [138, 200, 372, 600, 1000].every(n => harmonicForm(n, 50) < 0 && survivalLog10(n, 50) < 0 && survivalLog10(n, 50) > -Infinity));

  console.log('\n6. the companion figure: (cap/n)^n underflows in linear space, and does not in logs');
  ok('(50/n)^n is exactly 0 in a double from n = 372',
    Math.pow(50 / 372, 372) === 0 && Math.pow(50 / 370, 370) > 0,
    `n=370 ${Math.pow(50 / 370, 370).toExponential(2)}, n=372 ${Math.pow(50 / 372, 372)}`);
  ok('carried in logs the same quantity is 10^-1301.03 at the slider maximum',
    close(1000 * (Math.log10(50) - Math.log10(1000)), -1301.03, 0.01),
    (1000 * (Math.log10(50) - Math.log10(1000))).toFixed(4));

  console.log(`\n${fails === 0 ? 'all checks passed' : fails + ' FAILED'}`);
  process.exit(fails === 0 ? 0 : 1);
}
