#!/usr/bin/env node
// ─────────────────────────────────────────────────────────────────────────────
// Allowed, and Impossible — verifier for the stratum
//   /strata/allowed-and-impossible/
//
// The stratum's thesis: a *counting* condition is always NECESSARY for a
// combinatorial object to exist, but it is not always SUFFICIENT. Sometimes the
// arithmetic gives permission and the object still cannot be built. This file
// re-derives, from scratch, every quantitative claim the page makes, and keeps
// the cited-but-not-re-derived results clearly labelled.
//
// Run:  node research/allowed-and-impossible/verify.mjs
// Exit 0 iff every check passes. No imports, no network — pure arithmetic and
// an exhaustive census.
// ─────────────────────────────────────────────────────────────────────────────

let pass = 0, fail = 0;
const ser = (x) => (typeof x === "bigint" ? `${x}n` : JSON.stringify(x));
const eq = (got, want, label) => {
  const ok = ser(got) === ser(want);
  console.log(`${ok ? "  ok " : "FAIL "} ${label}${ok ? "" : `  got ${JSON.stringify(got)} want ${JSON.stringify(want)}`}`);
  ok ? pass++ : fail++;
};
const ok = (cond, label) => eq(!!cond, true, label);

// ═════════════════════════════════════════════════════════════════════════════
// PART 1 — Euler's 36 officers: no pair of orthogonal Latin squares of order 6.
//
// A Latin square L of order n has an orthogonal MATE  iff  L decomposes into n
// disjoint transversals. (Cells where the mate equals symbol k form a
// transversal, one per symbol; conversely, label the j-th transversal j.)
// "Has a mate" is invariant under permuting rows, permuting columns, and
// relabelling symbols — exactly the operations that REDUCE a Latin square (first
// row and first column in natural order). So testing every reduced square is a
// complete, exhaustive search over all Latin squares up to that equivalence.
//
//   reduced LS counts (independent published values): n=2→1, n=3→1, n=4→4,
//   n=5→56, n=6→9408. We regenerate and check these — a self-test of the
//   generator before we trust its verdict.
// ═════════════════════════════════════════════════════════════════════════════

function generateReduced(n) {
  const squares = [];
  const grid = Array.from({ length: n }, () => new Array(n).fill(-1));
  for (let c = 0; c < n; c++) grid[0][c] = c;
  for (let r = 0; r < n; r++) grid[r][0] = r;
  const rowSym = new Array(n).fill(0);
  const colSym = new Array(n).fill(0);
  for (let c = 0; c < n; c++) rowSym[0] |= 1 << grid[0][c];
  for (let r = 1; r < n; r++) rowSym[r] |= 1 << grid[r][0];
  for (let c = 0; c < n; c++) colSym[c] |= 1 << grid[0][c];
  for (let r = 1; r < n; r++) colSym[0] |= 1 << grid[r][0];
  const cells = [];
  for (let r = 1; r < n; r++) for (let c = 1; c < n; c++) cells.push([r, c]);
  function rec(idx) {
    if (idx === cells.length) { squares.push(grid.map((row) => row.slice())); return; }
    const [r, c] = cells[idx];
    for (let s = 0; s < n; s++) {
      const bit = 1 << s;
      if ((rowSym[r] & bit) || (colSym[c] & bit)) continue;
      grid[r][c] = s; rowSym[r] |= bit; colSym[c] |= bit;
      rec(idx + 1);
      grid[r][c] = -1; rowSym[r] &= ~bit; colSym[c] &= ~bit;
    }
  }
  rec(0);
  return squares;
}

function transversals(L, n) {
  const out = [];
  const choice = new Array(n);
  (function rec(r, colMask, symMask) {
    if (r === n) { out.push(choice.slice()); return; }
    for (let c = 0; c < n; c++) {
      const cb = 1 << c; if (colMask & cb) continue;
      const sb = 1 << L[r][c]; if (symMask & sb) continue;
      choice[r] = c; rec(r + 1, colMask | cb, symMask | sb);
    }
  })(0, 0, 0);
  return out;
}

function hasOrthogonalMate(L, n) {
  const ts = transversals(L, n);
  if (ts.length < n) return false;
  const masks = ts.map((t) => {
    let m = 0n;
    for (let r = 0; r < n; r++) m |= 1n << BigInt(r * n + t[r]);
    return m;
  });
  const FULL = (1n << BigInt(n * n)) - 1n;
  return (function rec(covered, used) {
    if (covered === FULL) return true;
    if (used === n) return false;
    let cell = 0; while ((covered >> BigInt(cell)) & 1n) cell++;
    const cellBit = 1n << BigInt(cell);
    for (const m of masks) {
      if (!(m & cellBit) || (m & covered)) continue;
      if (rec(covered | m, used + 1)) return true;
    }
    return false;
  })(0n, 0);
}

function census(n) {
  const sq = generateReduced(n);
  let withMate = 0;
  for (const L of sq) if (hasOrthogonalMate(L, n)) withMate++;
  return { reduced: sq.length, withMate };
}

console.log("PART 1 — orthogonal Latin squares / Euler's 36 officers");
const knownReduced = { 2: 1, 3: 1, 4: 4, 5: 56, 6: 9408 };
for (const n of [2, 3, 4, 5, 6]) {
  const { reduced, withMate } = census(n);
  eq(reduced, knownReduced[n], `order ${n}: reduced Latin squares = ${knownReduced[n]} (generator self-test)`);
  const exists = withMate > 0;
  // MOLS(n) exist for all n except 2 and 6.
  const shouldExist = n !== 2 && n !== 6;
  eq(exists, shouldExist, `order ${n}: a pair of orthogonal Latin squares ${shouldExist ? "EXISTS" : "DOES NOT EXIST"} (found ${withMate} reduced squares with a mate)`);
}
// The headline, stated plainly:
const six = census(6);
ok(six.reduced === 9408 && six.withMate === 0,
  "HEADLINE: all 9408 reduced order-6 Latin squares searched; 0 have an orthogonal mate ⇒ the 36 officers cannot be arranged (Tarry 1900; Euler 1782 conjectured it)");

// ═════════════════════════════════════════════════════════════════════════════
// PART 2 — the positive control: order 5 DOES admit a Graeco-Latin square.
// L1[i][j] = (i+j) mod 5,  L2[i][j] = (i+2j) mod 5. Orthogonal because the
// map (i,j) -> (i+j, i+2j) has determinant 1·2−1·1 = 1, a unit mod 5.
// All 25 ordered (rank, regiment) pairs are distinct ⇒ the officers stand.
// ═════════════════════════════════════════════════════════════════════════════
console.log("\nPART 2 — order 5 works (a complete superposition; positive control)");
{
  const n = 5;
  const L1 = (i, j) => (i + j) % n;
  const L2 = (i, j) => (i + 2 * j) % n;
  const seen = new Set();
  let latin1 = true, latin2 = true;
  // Latin check via row/col symbol sets
  for (let i = 0; i < n; i++) {
    const r1 = new Set(), r2 = new Set();
    for (let j = 0; j < n; j++) { r1.add(L1(i, j)); r2.add(L2(i, j)); }
    if (r1.size !== n) latin1 = false;
    if (r2.size !== n) latin2 = false;
  }
  for (let j = 0; j < n; j++) {
    const c1 = new Set(), c2 = new Set();
    for (let i = 0; i < n; i++) { c1.add(L1(i, j)); c2.add(L2(i, j)); }
    if (c1.size !== n) latin1 = false;
    if (c2.size !== n) latin2 = false;
  }
  for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) seen.add(L1(i, j) * n + L2(i, j));
  ok(latin1 && latin2, "order 5: both squares are Latin");
  eq(seen.size, 25, "order 5: all 25 (rank, regiment) pairs distinct ⇒ orthogonal (the officers stand)");
}

// ═════════════════════════════════════════════════════════════════════════════
// PART 3: the phantom perfect code [90, 78, 5]: sphere volumes balance, no code.
// A perfect 2-error-correcting binary code of length n needs its M correction
// spheres of radius 2 to tile {0,1}^n exactly:  M · (1 + n + C(n,2)) = 2^n.
// For n = 90: 1 + 90 + C(90,2) = 1 + 90 + 4005 = 4096 = 2^12, so M = 2^78 and
// 2^78 · 2^12 = 2^90 closes perfectly — yet no such code exists (van Lint 1971;
// Tietäväinen 1973). The arithmetic here is re-derived; the non-existence is
// CITED (classification theorem). See /strata/perfect-codes/.
// ═════════════════════════════════════════════════════════════════════════════
console.log("\nPART 3 — the [90,78,5] perfect-code phantom (sphere-packing arithmetic)");
{
  const choose2 = (n) => (n * (n - 1)) / 2;
  const vol = 1 + 90 + choose2(90);
  eq(choose2(90), 4005, "C(90,2) = 4005");
  eq(vol, 4096, "sphere volume 1 + 90 + C(90,2) = 4096");
  eq(vol, 2 ** 12, "= 2^12 exactly (the packing identity balances)");
  // 2^78 · 2^12 = 2^90  (use BigInt to be exact)
  eq((2n ** 78n) * (2n ** 12n), 2n ** 90n, "2^78 · 2^12 = 2^90 (equal total sphere volume; no tiling established)");
}

// ═════════════════════════════════════════════════════════════════════════════
// PART 4 — Bruck–Ryser–Chowla: the count permits order 10, computation kills it.
// For a projective plane of order n with n ≡ 1 or 2 (mod 4), BRC requires n to
// be a sum of two squares. We re-derive the sum-of-two-squares facts:
//   n=6  ≡ 2 (mod 4), NOT a sum of two squares ⇒ BRC already forbids it.
//   n=10 ≡ 2 (mod 4), 10 = 1² + 3²  ⇒ BRC PERMITS it — yet Lam, Thiel & Swiercz
//          (1989) proved by exhaustive computation that no such plane exists.
// The non-existence of the order-10 plane is CITED (Lam 1989), not re-derived.
// ═════════════════════════════════════════════════════════════════════════════
console.log("\nPART 4 — Bruck–Ryser–Chowla: 6 forbidden by the count, 10 permitted yet impossible");
{
  const sumOfTwoSquares = (n) => {
    for (let a = 0; a * a <= n; a++) {
      const b2 = n - a * a, b = Math.round(Math.sqrt(b2));
      if (b * b === b2) return [a, b];
    }
    return null;
  };
  const brcApplies = (n) => n % 4 === 1 || n % 4 === 2;
  ok(brcApplies(6), "order 6 ≡ 2 (mod 4): BRC applies");
  eq(sumOfTwoSquares(6), null, "6 is NOT a sum of two squares ⇒ BRC forbids a projective plane of order 6");
  ok(brcApplies(10), "order 10 ≡ 2 (mod 4): BRC applies");
  eq(sumOfTwoSquares(10), [1, 3], "10 = 1² + 3² ⇒ BRC PERMITS a plane of order 10 (the count says yes)");
  // cited: Lam, Thiel, Swiercz 1989 — no projective plane of order 10. Not re-derived (≈2000+ CPU-hours).
  ok(true, "no plane of order 10 exists — CITED (Lam, Thiel & Swiercz 1989); far beyond a from-scratch re-derivation");
}

// ═════════════════════════════════════════════════════════════════════════════
// PART 5 — the honest counterpoint: when the count DOES decide (Langford).
// A Langford pairing of order n exists iff n ≡ 0 or 3 (mod 4). The necessary
// counting condition (the triangular number T_n = n(n+1)/2 must be even) is here
// ALSO sufficient (Davies 1959 construction). We check the parity predicate
// against the brute-force existence for small n — necessity AND sufficiency
// agree, so for Langford the count is the whole story. (Re-derived independently
// here; the construction sufficiency is cited. See /strata/langford-pairings/.)
// ═════════════════════════════════════════════════════════════════════════════
console.log("\nPART 5 — Langford pairings: a case where the count decides (necessary AND sufficient)");
{
  // brute-force existence of a Langford pairing of order n
  function langfordExists(n) {
    const slots = new Array(2 * n).fill(0);
    function place(k) {
      if (k > n) return true;
      for (let i = 0; i + k + 1 < 2 * n; i++) {
        const j = i + k + 1;
        if (slots[i] === 0 && slots[j] === 0) {
          slots[i] = slots[j] = k;
          if (place(k + 1)) return true;
          slots[i] = slots[j] = 0;
        }
      }
      return false;
    }
    return place(1);
  }
  const triangularEven = (n) => ((n * (n + 1)) / 2) % 2 === 0; // ⇔ n ≡ 0,3 (mod 4)
  for (let n = 1; n <= 11; n++) {
    eq(langfordExists(n), triangularEven(n),
      `Langford n=${n}: brute-force existence ${langfordExists(n) ? "yes" : "no "} matches the parity count ${triangularEven(n)}`);
  }
}

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