// hamming.mjs — verify the Hamming(7,4) code from scratch, in F2.
//   node research/perfect-codes/hamming.mjs
//
// Proves, by direct enumeration:
//   (1) the [7,4] code has 16 codewords and minimum distance 3 (corrects 1 error);
//   (2) PERFECTION — the 16 Hamming balls of radius 1 partition all 2^7 = 128
//       binary strings exactly: every string lies within one flip of EXACTLY one
//       codeword (no gaps, no overlap), i.e. 16 * (1 + 7) = 128;
//   (3) syndrome decoding corrects every single-bit error: the syndrome H·rᵀ is
//       precisely the binary index of the flipped position.
//
// Convention: the 3x7 parity-check matrix H has, as its columns, the binary
// numerals 1..7 (this is the classic "syndrome = position" Hamming layout).

const N = 7, K = 4, R = N - K; // [7,4], 3 parity bits

// --- parity-check matrix H (R x N): column j (0-indexed) is the binary of j+1 ---
// rows are the 3 bits (LSB first), so H[b][j] = bit b of (j+1).
const H = Array.from({ length: R }, (_, b) =>
  Array.from({ length: N }, (_, j) => ((j + 1) >> b) & 1));

// columns of H, as integers 1..7 — the syndrome a flipped bit j produces.
const syndromeOfBit = j => H.reduce((s, row, b) => s | (row[j] << b), 0); // = j+1

// --- build a generator: pick the 4 columns that are NOT powers of two as the
// message positions, the 3 power-of-two columns as parity. Then encode by solving
// H·cᵀ = 0. We enumerate codewords directly instead: c in {0,1}^7 is a codeword
// iff H·cᵀ = 0 (mod 2).
const dot = (row, vec) => row.reduce((s, h, j) => s ^ (h & ((vec >> j) & 1)), 0);
const syndrome = vec => H.reduce((s, row, b) => s | (dot(row, vec) << b), 0);

const codewords = [];
for (let v = 0; v < (1 << N); v++) if (syndrome(v) === 0) codewords.push(v);

const popcount = x => { let c = 0; while (x) { c += x & 1; x >>= 1; } return c; };
const dist = (a, b) => popcount(a ^ b);

let pass = 0, fail = 0;
const check = (cond, msg) => { (cond ? pass++ : fail++); console.log((cond ? '  ✓ ' : '  ✗ ') + msg); };

console.log('Hamming(7,4) over F2 — parity-check H columns = binary 1..7\n');

// (1) size and minimum distance
check(codewords.length === 16, `code has 16 codewords (2^${K})  [got ${codewords.length}]`);
let dmin = Infinity;
for (let i = 0; i < codewords.length; i++)
  for (let j = i + 1; j < codewords.length; j++)
    dmin = Math.min(dmin, dist(codewords[i], codewords[j]));
check(dmin === 3, `minimum distance d = 3  ⇒ corrects t = ⌊(d-1)/2⌋ = 1 error  [got ${dmin}]`);

// (2) PERFECTION — partition of F2^7 by radius-1 balls
const owner = new Array(1 << N).fill(-1);
let multiplyCovered = 0;
for (const c of codewords) {
  // the ball of radius 1 around c: c itself and its 7 single-bit neighbours
  const ball = [c];
  for (let b = 0; b < N; b++) ball.push(c ^ (1 << b));
  for (const x of ball) { if (owner[x] !== -1) multiplyCovered++; owner[x] = c; }
}
const uncovered = owner.filter(o => o === -1).length;
check(multiplyCovered === 0, `no string is covered twice (balls are disjoint)  [overlaps ${multiplyCovered}]`);
check(uncovered === 0, `no string is left uncovered (balls fill F2^7)  [gaps ${uncovered}]`);
check(16 * (1 + 7) === 128, `sphere-packing identity: 16·(1+7) = 128 = 2^7 exactly`);

// (3) syndrome decoding corrects every single-bit error
let corrected = 0, total = 0;
for (const c of codewords) {
  for (let b = 0; b < N; b++) {
    total++;
    const received = c ^ (1 << b);
    const s = syndrome(received);            // syndrome of the error
    check_silent(s === syndromeOfBit(b), b, c);
    const fixed = received ^ (1 << (s - 1)); // flip the bit the syndrome names
    if (fixed === c) corrected++;
  }
}
function check_silent() {}
check(corrected === total && total === 16 * 7,
  `all ${total} single-bit errors corrected by syndrome decoding (syndrome = flipped position)`);

// the syndrome literally equals position+1 for each bit
const syndromeMap = Array.from({ length: N }, (_, b) => syndromeOfBit(b));
check(syndromeMap.every((s, b) => s === b + 1),
  `syndrome of flipping bit j is exactly j+1: [${syndromeMap.join(', ')}]`);

console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
