#!/usr/bin/env node
// verify.mjs — the load-bearing claims of the portal "The Number Behind the Door"
// (a combine portal walking the harmonic number H_n = 1 + 1/2 + … + 1/n across
//  three strata: the coupon collector, the secretary/records problem, and the
//  100-prisoners loop).
//
// Run:  node research/harmonic-numbers-portal/verify.mjs
// No dependencies. Exact (BigInt rationals + full enumeration) where it matters.
//
// The portal's central, non-obvious claim — the one NONE of the three member
// pages states — is that two of them are not merely analogous but count the SAME
// statistic on a random permutation: the number of RECORDS (left-to-right maxima,
// the secretary problem's engine) is equidistributed with the number of CYCLES
// (the prisoners' loop structure), via the fundamental bijection of Foata. Both
// have mean exactly H_n. We prove the bijection by exhaustive enumeration.

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;

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 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}`;

function* perms(arr) {
  if (arr.length <= 1) { yield arr.slice(); return; }
  for (let i = 0; i < arr.length; i++) {
    const rest = arr.slice(0, i).concat(arr.slice(i + 1));
    for (const p of perms(rest)) yield [arr[i], ...p];
  }
}
const range = (n) => Array.from({ length: n }, (_, i) => i);
const Hsum = (n) => { let H = Frac(0); for (let k = 1; k <= n; k++) H = fadd(H, Frac(1, k)); return H; };

console.log("\n  THE NUMBER BEHIND THE DOOR — portal verifier");
console.log("  H_n across the coupon collector, the secretary problem, and the 100-prisoners loop\n");

// ===========================================================================
// PART 1 — RECORDS and CYCLES are the SAME statistic (the fundamental bijection)
// ===========================================================================
console.log("  Part 1 — records ≡ cycles (Foata's fundamental bijection)\n");

// A permutation given in one-line form p (p[i] = image of i, 0-indexed).
// # records (left-to-right maxima):
function numRecords(p) { let mx = -1, c = 0; for (const x of p) if (x > mx) { mx = x; c++; } return c; }
// # cycles of the permutation as a function i ↦ p[i]:
function numCycles(p) {
  const seen = new Array(p.length).fill(false); let c = 0;
  for (let i = 0; i < p.length; i++) if (!seen[i]) { c++; let j = i; while (!seen[j]) { seen[j] = true; j = p[j]; } }
  return c;
}
// THE BIJECTION (Foata). Decompose p into cycles; write each cycle starting at
// its LARGEST element; order the cycles by INCREASING largest element; drop the
// parentheses → a one-line word. Claim: # left-to-right maxima of the word = #
// cycles of p. (Each cycle-leader is a new maximum; no follower ever is.)
function foata(p) {
  const n = p.length, seen = new Array(n).fill(false), cycles = [];
  for (let i = 0; i < n; i++) if (!seen[i]) {
    const cyc = []; let j = i; while (!seen[j]) { seen[j] = true; cyc.push(j); j = p[j]; }
    // rotate so the largest element is first
    let mi = 0; for (let k = 1; k < cyc.length; k++) if (cyc[k] > cyc[mi]) mi = k;
    cycles.push(cyc.slice(mi).concat(cyc.slice(0, mi)));
  }
  cycles.sort((a, b) => a[0] - b[0]);   // increasing leader
  return cycles.flat();
}
{
  let bijOK = true, recEqCyc = true;
  for (const n of [1, 2, 3, 4, 5, 6, 7]) {
    const images = new Set();
    for (const p of perms(range(n))) {
      const w = foata(p);
      images.add(w.join(","));
      if (numRecords(w) !== numCycles(p)) recEqCyc = false;
    }
    let fact = 1; for (let k = 2; k <= n; k++) fact *= k;
    if (images.size !== fact) bijOK = false;   // it is a bijection (image = all of S_n)
  }
  log(recEqCyc, `# records of foata(p) = # cycles of p, for every p, all n≤7`);
  log(bijOK, `foata is a bijection on S_n (image hits all n! permutations), all n≤7`);
}

// The consequence: the NUMBER OF RECORDS and the NUMBER OF CYCLES have the SAME
// distribution — the unsigned Stirling numbers of the first kind c(n,k) — so in
// particular the SAME mean, H_n. We check both distributions equal c(n,k), and
// the shared mean is H_n exactly.
{
  // unsigned Stirling first kind via recurrence c(n,k)=c(n-1,k-1)+(n-1)c(n-1,k)
  function stirling(n) {
    let row = [1n];
    for (let m = 1; m <= n; m++) {
      const next = new Array(m + 1).fill(0n);
      for (let k = 1; k <= m; k++) next[k] = (row[k - 1] || 0n) + BigInt(m - 1) * (row[k] || 0n);
      row = next;
    }
    return row; // row[k] = c(n,k), k=0..n  (row[0]=0 for n>=1)
  }
  let distOK = true, meanOK = true;
  for (const n of [1, 2, 3, 4, 5, 6, 7]) {
    const c = stirling(n);
    const recCount = new Array(n + 1).fill(0n), cycCount = new Array(n + 1).fill(0n);
    let total = 0n, recSum = 0n, cycSum = 0n;
    for (const p of perms(range(n))) {
      total++;
      const r = numRecords(p), y = numCycles(p);
      recCount[r]++; cycCount[y]++; recSum += BigInt(r); cycSum += BigInt(y);
    }
    for (let k = 1; k <= n; k++) if (recCount[k] !== c[k] || cycCount[k] !== c[k]) distOK = false;
    const meanRec = Frac(recSum, total), meanCyc = Frac(cycSum, total), Hn = Hsum(n);
    if (!feq(meanRec, Hn) || !feq(meanCyc, Hn)) meanOK = false;
  }
  log(distOK, `dist(#records) = dist(#cycles) = unsigned Stirling 1st kind c(n,k), all n≤7`);
  log(meanOK, `E[#records] = E[#cycles] = H_n exactly, all n≤7 (the two problems share one mean)`);
}

// ===========================================================================
// PART 2 — THE SECRETARY FACE:  H_n → the 1/e limit
// ===========================================================================
console.log("\n  Part 2 — the secretary face: H_n, then 1/e\n");

// The expected number of records is H_n (Part 1). The best-choice win prob for
// threshold r is P(r) = (r−1)/n · Σ_{j=r}^{n} 1/(j−1); optimum → 1/e. (Verified
// in full in research/look-then-leap/; here we re-confirm the limit independently.)
{
  function optimalFloat(n) {
    const suf = new Float64Array(n + 2);
    for (let j = n - 1; j >= 1; j--) suf[j] = suf[j + 1] + 1 / j;
    let bestP = 1 / n; for (let r = 2; r <= n; r++) { const p = (r - 1) / n * suf[r - 1]; if (p > bestP) bestP = p; }
    return bestP;
  }
  const INV_E = 1 / Math.E;
  const p6 = optimalFloat(1000000);
  log(approx(p6, INV_E, 5e-4), `best-choice win probability → 1/e = ${INV_E.toFixed(6)} (n=10⁶: ${p6.toFixed(6)})`);
  // H_n appears as E[records]; the cutoff solves a harmonic tail-sum = 1.
  let Hn = 0; for (let k = 1; k <= 1000; k++) Hn += 1 / k;   // float (exact rational here has a 430-digit numerator)
  log(approx(Hn, Math.log(1000) + 0.5772156649, 1e-3), `E[records] at n=1000 is H_1000 = ${Hn.toFixed(4)} ≈ ln 1000 + γ`);
}

// ===========================================================================
// PART 3 — THE PRISONERS' FACE:  H_n − H_{n/2} → 1 − ln 2
// ===========================================================================
console.log("\n  Part 3 — the prisoners' face: H_n − H_{n/2}, then 1 − ln 2\n");

// In a random permutation of n=2m, the chance the LONGEST cycle exceeds m is the
// chance a cycle of length ℓ>m exists; for ℓ>m there is at most one, and the
// probability a cycle of length exactly ℓ exists is 1/ℓ. So
//   P(longest > m) = Σ_{ℓ=m+1}^{2m} 1/ℓ = H_{2m} − H_m  → ln 2.
// Survival of the loop strategy = 1 − that  → 1 − ln 2.
{
  // (A) the 1/ℓ fact and the sum, exact rationals.
  // (B) brute force: enumerate all permutations of small even n, count those whose
  //     longest cycle ≤ n/2 (the prisoners survive), compare to 1 − (H_n − H_{n/2}).
  function longestCycle(p) {
    const seen = new Array(p.length).fill(false); let mxlen = 0;
    for (let i = 0; i < p.length; i++) if (!seen[i]) { let j = i, len = 0; while (!seen[j]) { seen[j] = true; len++; j = p[j]; } if (len > mxlen) mxlen = len; }
    return mxlen;
  }
  let allOK = true, lines = [];
  for (const n of [2, 4, 6, 8]) {
    const m = n / 2;
    let survive = 0n, total = 0n;
    for (const p of perms(range(n))) { total++; if (longestCycle(p) <= m) survive++; }
    const empirical = Frac(survive, total);
    const formula = fsub(Frac(1), fsub(Hsum(n), Hsum(m)));   // 1 − (H_n − H_{n/2})
    if (!feq(empirical, formula)) allOK = false;
    lines.push(`n=${n}: ${fstr(empirical)}`);
  }
  log(allOK, `P(loop survival) = 1 − (H_n − H_{n/2}) exactly, n=2,4,6,8 (enumeration = formula): ${lines.join(", ")}`);
  // the limits
  const big = 100000; let Hn = 0, Hh = 0; for (let k = 1; k <= big; k++) { Hn += 1 / k; if (k <= big / 2) Hh += 1 / k; }
  log(approx(Hn - Hh, Math.log(2), 1e-4), `H_n − H_{n/2} → ln 2 = ${Math.log(2).toFixed(6)} (n=10⁵: ${(Hn - Hh).toFixed(6)})`);
  log(approx(1 - (Hn - Hh), 1 - Math.log(2), 1e-4), `loop survival → 1 − ln 2 = ${(1 - Math.log(2)).toFixed(6)} (≈ 30.69%)`);
}

// ===========================================================================
// PART 4 — THE COLLECTOR'S FACE:  n·H_n, and the same H_n − H_{n/2}
// ===========================================================================
console.log("\n  Part 4 — the collector's face: n·H_n, and the same half-sum\n");

// Coupon collector: E[T] = n·H_n (proved in research/coupon-collector/). The
// portal's bridge: for even n, the FIRST half of the collection (from zero to n/2
// distinct) costs n·(H_n − H_{n/2}) on average, literally the prisoners' quantity
// scaled by n; divided by n it tends to ln 2. The second half (n/2 to n) costs n·H_{n/2}.
{
  function expFormula(n) { let H = Frac(0); for (let j = 1; j <= n; j++) H = fadd(H, Frac(1, j)); return Frac(BigInt(n) * H.n, H.d); }
  // sanity: 6·H_6 = 147/10
  log(feq(expFormula(6), Frac(147, 10)), `coupon collector E[T] = n·H_n (die: 6·H_6 = 147/10 = 14.7)`);
  const n = 10000; let Hn = 0, Hh = 0; for (let k = 1; k <= n; k++) { Hn += 1 / k; if (k <= n / 2) Hh += 1 / k; }
  const firstHalf = n * (Hn - Hh);
  // phase sum: holding k distinct coupons, the next new one costs n/(n−k) draws on average
  let firstPhases = 0; for (let k = 0; k < n / 2; k++) firstPhases += n / (n - k);
  log(approx(firstHalf, firstPhases, 1e-6) && approx(firstHalf / n, Math.log(2), 1e-3), `first half of the collection (0 to n/2 distinct) costs n·(H_n − H_{n/2}) = ${firstHalf.toFixed(1)} draws on average at n=${n} (the prisoners' sum, scaled by n); divided by n it tends to ln 2`);
}

// ===========================================================================
// PART 5 — THE COMMON ENGINE:  H_n = ln n + γ, the slow climb that ties it all
// ===========================================================================
console.log("\n  Part 5 — the common engine: H_n = ln n + γ + o(1)\n");

{
  const GAMMA = 0.5772156649015329;
  let H = 0; for (let k = 1; k <= 1000000; k++) H += 1 / k;
  const gap = H - Math.log(1000000);
  log(approx(gap, GAMMA, 1e-6), `H_n − ln n → γ = ${GAMMA.toFixed(9)} (n=10⁶: ${gap.toFixed(9)})`);
  // the three transcendental constants are all decided by the harmonic series:
  //   1/e (secretary), 1 − ln 2 (prisoners), and γ inside n·H_n (collector).
  log(approx(1 / Math.E, 0.36787944, 1e-6) && approx(1 - Math.log(2), 0.30685282, 1e-6),
    `the three limits — 1/e=${(1 / Math.E).toFixed(5)}, 1−ln2=${(1 - Math.log(2)).toFixed(5)}, γ=${GAMMA.toFixed(5)} — are all read off the same Σ1/k`);
}

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