AI 代码评审实战:用 JavaScript BigInt 构建可验证的异或线性基
从可表示性到最大子集异或,把算法结论变成能够复核的代码证据。

一、先审契约:固定宽度由谁保证
设想一次 AI 辅助代码评审:需求是维护若干个非负整数,允许选择其中任意子集,对选中项做异或;随后回答一个新值是否能被表示,以及从指定初值出发,能得到的最大异或结果。模型很容易给出几十行看起来熟悉的循环,真正需要审的却是输入范围、循环不变量和返回结果的含义。本文是一组为讲解构造的评审情境,不是某个真实模型或项目的失败记录,也不包含模型能力排名或性能跑分。
这里固定一个位宽 W,把合法值限定为零到二的 W 次方减一。每个值可看作由 W 个零或一组成的向量;相加采用异或,相同位上的两个一会相消。我们关心的是这些向量张成的空间,和字符串进制转换、标志位开关不同。选择一个输入两次等于没有选择它,因此用子集已经足够描述全部结果。
JavaScript 的 BigInt 不会因为变量名叫 uint64 就自动变成六十四位无符号数。下面把类型与范围检查放在入口,越界直接报错。为控制教学实现的资源规模,W 限制在一到一千零二十四;这是一项接口选择,不是语言的固有限制。位下标仍可使用 Number,参与 BigInt 位移时显式转成 BigInt。
ECMAScript 的 BigInt 位移定义和二元运算求值规则给出了相应的类型语义。另一个易混点是BigInt.asUintN:它按给定位宽取模,不能替代本接口的拒绝越界。第一个断言组刻意把这些边界写成可执行事实。
示例 1:独立运行的 01.cjs。
'use strict';
const assert = require('node:assert/strict');
function makeCheck(width) {
if (!Number.isInteger(width) || width < 1 || width > 1024)
throw new RangeError('width must be 1..1024');
const limit = 1n << BigInt(width);
return value => {
if (typeof value !== 'bigint') throw new TypeError('BigInt required');
if (value < 0n || value >= limit) throw new RangeError('out of width');
return value;
};
}
const check64 = makeCheck(64);
assert.equal(check64(1n << 63n), 9223372036854775808n);
assert.throws(() => check64(1), TypeError);
assert.throws(() => check64(-1n), RangeError);
assert.throws(() => check64(1n << 64n), RangeError);
assert.equal(BigInt.asUintN(3, 8n), 0n);
assert.equal(1 << 40, 256);
assert.equal(1n << 40n, 1099511627776n);
assert.throws(() => 1n ^ 1, TypeError);
console.log('01 contract OK');实际输出:
01 contract OK
全文九段代码都是独立的 CommonJS 文件,无第三方依赖。分别保存为 01.cjs 到 09.cjs,用 node --unhandled-rejections=strict 01.cjs 这样的命令运行;不需要把上一段的类粘贴过来。以下输出来自 Node.js v24.19.0 的实际执行,断言使用Node.js 严格断言接口。前四段为了展示算法保留了公开数组,后面的完整类使用私有字段保护状态。
二、插入不是去重:用最高位消元维护秩
用 rows[i] 保存最高有效位恰好位于 i 的非零向量,空槽以零表示。插入时从最高位向下看:当前值在这一位为零就跳过;若槽里已有向量,就异或掉这一位;若槽为空,当前残值就是一个新方向,保存它并让秩加一。一路消成零则说明原输入已在旧空间中,秩不变。
关键不变量有两条。第一,处理到第 i 位时,当前残值更高的位全部为零,因此后续消元不会把已经消掉的高位重新点亮。第二,原输入始终等于当前残值与若干旧基向量的异或。遇到空槽时,旧空间无法消去这个新的最高位;这就是独立性的依据。反过来,残值为零已经给出可表示的证明。
例子中的三、五、六互不相同,却满足三异或五等于六。因此普通 Set 的元素数不是秩。零向量和重复插入也不增加秩。若秩为 r,每个独立方向选或不选,恰好产生二的 r 次方个不同结果:不同选择若碰撞,二者异或便给出非空的基向量依赖关系,和独立性矛盾。
示例 2:独立运行的 02.cjs。
'use strict';
const assert = require('node:assert/strict');
function makeCheck(width) {
if (!Number.isInteger(width) || width < 1 || width > 1024)
throw new RangeError('width must be 1..1024');
const limit = 1n << BigInt(width);
return value => {
if (typeof value !== 'bigint') throw new TypeError('BigInt required');
if (value < 0n || value >= limit) throw new RangeError('out of width');
return value;
};
}
class Basis {
constructor(width) {
this.check = makeCheck(width);
this.rows = Array(width).fill(0n);
this.rank = 0;
}
insert(value) {
let x = this.check(value);
for (let i = this.rows.length - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
if (this.rows[i] !== 0n) x ^= this.rows[i];
else { this.rows[i] = x; this.rank++; return true; }
}
return false;
}
}
const b = new Basis(3);
assert.deepEqual([3n, 5n, 6n, 0n, 3n].map(x => b.insert(x)),
[true, true, false, false, false]);
assert.equal(b.rank, 2);
assert.deepEqual(b.rows, [0n, 3n, 5n]);
assert.equal(3n ^ 5n, 6n);
console.log('02 rank=2, reachable=4');实际输出:
02 rank=2, reachable=4
请注意,槽里保存的可能是消元后的组合,并不一定是某个原始输入。这不影响它表示同一个空间,却直接影响后面如何追踪来源。无需在插入时把所有旧向量反向清零成唯一标准形;这里的三角形结构已经足以支持后续查询。
三、成员查询:问的是能否组合,不是有没有原值
成员查询同样从最高位开始消元,但不修改基。目标最终归零就表示存在一个子集;残留非零说明无法表示。下面的简化写法遇到空槽会异或零并继续,最终检查残值;完整实现则会在缺少必要主元时提前返回。两种写法依据的是同一个事实:低位主元不能修补一个尚未消掉的高位。
空子集的异或约定为零,所以即使没有插入任何数,零也必须被判为可表示。如果产品需要非空子集,这个接口不能直接回答,特别是零的情况需要另外分析输入是否存在线性依赖。不要为了迎合业务措辞偷偷把空子集删掉,否则秩对应的计数和后面的穷举基准都会变义。
示例 3:独立运行的 03.cjs。
'use strict';
const assert = require('node:assert/strict');
function makeCheck(width) {
if (!Number.isInteger(width) || width < 1 || width > 1024)
throw new RangeError('width must be 1..1024');
const limit = 1n << BigInt(width);
return value => {
if (typeof value !== 'bigint') throw new TypeError('BigInt required');
if (value < 0n || value >= limit) throw new RangeError('out of width');
return value;
};
}
class Basis {
constructor(width) {
this.check = makeCheck(width);
this.rows = Array(width).fill(0n);
this.rank = 0;
}
insert(value) {
let x = this.check(value);
for (let i = this.rows.length - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
if (this.rows[i] !== 0n) x ^= this.rows[i];
else { this.rows[i] = x; this.rank++; return true; }
}
return false;
}
has(value) {
let x = this.check(value);
for (let i = this.rows.length - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) !== 0n) x ^= this.rows[i];
}
return x === 0n;
}
}
const b = new Basis(3);
[3n, 5n].forEach(x => b.insert(x));
for (const x of [0n, 3n, 5n, 6n]) assert.equal(b.has(x), true);
for (const x of [1n, 2n, 4n, 7n]) assert.equal(b.has(x), false);
assert.equal(new Basis(3).has(0n), true);
assert.throws(() => b.has(8n), RangeError);
assert.equal(b.rank, 2);
console.log('03 membership OK');实际输出:
03 membership OK
查询参数也经过相同的固定宽度校验。把越界目标直接返回 false 看似方便,却混淆了合法但不可表示与调用者传错数据两种情况。错误处理也是契约的一部分,不能让模型在不同方法里自行选择不同策略。
四、最大异或:贪心为什么必须从高位开始
maximizeXor(seed) 的含义是:在全部可表示值 s 中,最大化 seed 异或 s。省略 seed 时从零开始。由于所有值都是固定宽度非负整数,数值大小等价于从高位向低位比较,遇到的第一个不同位决定胜负。处理某个主元时,它不改变更高位,所以只要异或后数值更大,就可以接受这一步。
这个决策不会被未来低位向量推翻:未来所有主元都更低,已经确定的高位不再改变。更严格地说,按主元从高到低,每一步确定当前最高尚可控制位的最佳取值,低位的得失不足以抵消这一位的优势。这是三角形结构与非负比较共同提供的证明,不是因为异或运算天然适合所有贪心。
反例也要跟着证明走。插入三和一后,若按槽的低位顺序扫描,从零先变成一,再变成二,最后错过三;高位优先则得到正确答案。初值四的反例还说明,求 seed 的最优搭配并不是先算无初值最大值再机械异或 seed。下面同时检查空基、非零初值和错误扫描顺序。
示例 4:独立运行的 04.cjs。
'use strict';
const assert = require('node:assert/strict');
function makeCheck(width) {
if (!Number.isInteger(width) || width < 1 || width > 1024)
throw new RangeError('width must be 1..1024');
const limit = 1n << BigInt(width);
return value => {
if (typeof value !== 'bigint') throw new TypeError('BigInt required');
if (value < 0n || value >= limit) throw new RangeError('out of width');
return value;
};
}
class Basis {
constructor(width) {
this.check = makeCheck(width);
this.rows = Array(width).fill(0n);
this.rank = 0;
}
insert(value) {
let x = this.check(value);
for (let i = this.rows.length - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
if (this.rows[i] !== 0n) x ^= this.rows[i];
else { this.rows[i] = x; this.rank++; return true; }
}
return false;
}
maximizeXor(seed = 0n) {
let best = this.check(seed);
for (let i = this.rows.length - 1; i >= 0; i--) {
const candidate = best ^ this.rows[i];
if (candidate > best) best = candidate;
}
return best;
}
}
const b = new Basis(3);
[3n, 5n].forEach(x => b.insert(x));
assert.equal(b.maximizeXor(), 6n);
assert.equal(b.maximizeXor(1n), 7n);
assert.equal(b.maximizeXor(4n), 7n);
assert.notEqual(b.maximizeXor(4n), b.maximizeXor() ^ 4n);
assert.equal(new Basis(3).maximizeXor(4n), 4n);
const trap = new Basis(2);
[3n, 1n].forEach(x => trap.insert(x));
let wrong = 0n;
for (const row of trap.rows) if ((wrong ^ row) > wrong) wrong ^= row;
assert.equal(wrong, 2n);
assert.equal(trap.maximizeXor(), 3n);
console.log('04 max=6, seeded max=7; ascending trap caught');实际输出:
04 max=6, seeded max=7; ascending trap caught
此处的 Basis.maximizeXor 返回一个 BigInt。下一节增加来源证据后,完整 XorBasis 的同名方法会返回包含 value 与 indices 的对象,调用者应读取 value。本文不把两套教学阶段的返回类型混用。
五、加入来源证据:值消元,索引也同步消元
一个最大值本身还不足以解释业务结果。我们要返回原始输入的下标,使调用者能直接重新异或验证。为每次合法插入分配一个顺序编号,把相应的一位标记作为来源掩码;每个主元同时保存 value 和 mask。数值异或某一行时,来源掩码也异或同一行的掩码。
这里使用异或而不是并集至关重要。同一个原始项如果在两条组合路径里出现两次,数值贡献会抵消,来源中也应删除它。来源掩码的第 i 位只表达是否选择第 i 次输入,与数值的第 i 位没有任何对应关系。数值宽度是 W,来源位数随插入次数增长,这两种尺度需要分开评估。
下方是完整实现,随后三段会为独立运行而重复它。represent 返回一个可行子集,无法表示时返回 null;零返回空数组。maximizeXor 返回最优结果及其子集下标,初值不在下标列表里。size 记录全部合法插入次数,rank 只记录独立方向数量。本实现还限制最多四千零九十六次合法插入,防止来源编号无限增长。
示例 5:独立运行的 05.cjs。
'use strict';
const assert = require('node:assert/strict');
function makeCheck(width) {
if (!Number.isInteger(width) || width < 1 || width > 1024)
throw new RangeError('width must be 1..1024');
const limit = 1n << BigInt(width);
return value => {
if (typeof value !== 'bigint') throw new TypeError('BigInt required');
if (value < 0n || value >= limit) throw new RangeError('out of width');
return value;
};
}
class XorBasis {
#width; #check; #rows; #rank = 0; #size = 0;
constructor(width) {
this.#check = makeCheck(width);
this.#width = width;
this.#rows = Array(width).fill(null);
}
get rank() { return this.#rank; }
get size() { return this.#size; }
#indices(mask) {
const out = [];
for (let i = 0; mask !== 0n; i++, mask >>= 1n)
if ((mask & 1n) !== 0n) out.push(i);
return out;
}
insert(value) {
let x = this.#check(value);
if (this.#size >= 4096) throw new RangeError('item limit reached');
let mask = 1n << BigInt(this.#size++);
for (let i = this.#width - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
const row = this.#rows[i];
if (row) { x ^= row.value; mask ^= row.mask; }
else {
this.#rows[i] = { value: x, mask };
this.#rank++;
return { independent: true, relation: null };
}
}
return { independent: false, relation: this.#indices(mask) };
}
#reduce(value) {
let x = this.#check(value), mask = 0n;
for (let i = this.#width - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
const row = this.#rows[i];
if (!row) return { value: x, mask };
x ^= row.value; mask ^= row.mask;
}
return { value: x, mask };
}
has(value) { return this.#reduce(value).value === 0n; }
represent(value) {
const reduced = this.#reduce(value);
return reduced.value === 0n ? this.#indices(reduced.mask) : null;
}
maximizeXor(seed = 0n) {
let best = this.#check(seed), mask = 0n;
for (let i = this.#width - 1; i >= 0; i--) {
const row = this.#rows[i];
if (row && (best ^ row.value) > best) {
best ^= row.value; mask ^= row.mask;
}
}
return { value: best, indices: this.#indices(mask) };
}
}
const values = [3n, 5n, 6n];
const b = new XorBasis(3);
values.forEach(x => b.insert(x));
const witness = b.represent(6n);
assert.deepEqual(witness, [0, 1]);
assert.equal(witness.reduce((x, i) => x ^ values[i], 0n), 6n);
assert.equal(b.represent(7n), null);
assert.deepEqual(b.represent(0n), []);
const best = b.maximizeXor(1n);
assert.equal(best.value, 7n);
assert.equal(best.indices.reduce((x, i) => x ^ values[i], 1n), best.value);
witness.push(999);
assert.deepEqual(b.represent(6n), [0, 1]);
console.log('05 witness=[0,1], seeded max=7');实际输出:
05 witness=[0,1], seeded max=7
重新计算 witness 对应的异或,比检查它是不是某个预期数组更稳健,因为同一个目标可能有多种表示。这里额外检查固定顺序下的具体结果,只用于示范追踪过程。返回的数组是新建的,调用者改动它不会污染内部主元。完整类也不开放行数组,避免外部改写破坏证明所依赖的不变量。
六、线性相关也有证据:插入返回一条零和关系
相关输入不是错误,它只是没有给空间增加新方向。完整类在这种情况下返回 relation,其中包含这次输入的下标以及若干此前下标,所列数值的异或必定为零。因为初始来源掩码只有新输入那一位,而旧行不可能包含未来编号,消元结束后新下标一定还在关系里。
这个证据可以帮助评审者区分三种情况:一个值由多个旧值组合得到;一个值和旧值完全重复;以及输入本身是零。它们对秩的影响相同,解释却不同。例子分别得到下标零、一、二组成的关系,单独下标三组成的关系,以及下标零、四组成的关系。来源编号依赖插入顺序,不能误当成跨实例稳定标识。
示例 6:独立运行的 06.cjs。
'use strict';
const assert = require('node:assert/strict');
function makeCheck(width) {
if (!Number.isInteger(width) || width < 1 || width > 1024)
throw new RangeError('width must be 1..1024');
const limit = 1n << BigInt(width);
return value => {
if (typeof value !== 'bigint') throw new TypeError('BigInt required');
if (value < 0n || value >= limit) throw new RangeError('out of width');
return value;
};
}
class XorBasis {
#width; #check; #rows; #rank = 0; #size = 0;
constructor(width) {
this.#check = makeCheck(width);
this.#width = width;
this.#rows = Array(width).fill(null);
}
get rank() { return this.#rank; }
get size() { return this.#size; }
#indices(mask) {
const out = [];
for (let i = 0; mask !== 0n; i++, mask >>= 1n)
if ((mask & 1n) !== 0n) out.push(i);
return out;
}
insert(value) {
let x = this.#check(value);
if (this.#size >= 4096) throw new RangeError('item limit reached');
let mask = 1n << BigInt(this.#size++);
for (let i = this.#width - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
const row = this.#rows[i];
if (row) { x ^= row.value; mask ^= row.mask; }
else {
this.#rows[i] = { value: x, mask };
this.#rank++;
return { independent: true, relation: null };
}
}
return { independent: false, relation: this.#indices(mask) };
}
#reduce(value) {
let x = this.#check(value), mask = 0n;
for (let i = this.#width - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
const row = this.#rows[i];
if (!row) return { value: x, mask };
x ^= row.value; mask ^= row.mask;
}
return { value: x, mask };
}
has(value) { return this.#reduce(value).value === 0n; }
represent(value) {
const reduced = this.#reduce(value);
return reduced.value === 0n ? this.#indices(reduced.mask) : null;
}
maximizeXor(seed = 0n) {
let best = this.#check(seed), mask = 0n;
for (let i = this.#width - 1; i >= 0; i--) {
const row = this.#rows[i];
if (row && (best ^ row.value) > best) {
best ^= row.value; mask ^= row.mask;
}
}
return { value: best, indices: this.#indices(mask) };
}
}
const values = [3n, 5n, 6n, 0n, 3n];
const b = new XorBasis(3);
const results = values.map(x => b.insert(x));
assert.deepEqual(results[2], { independent: false, relation: [0, 1, 2] });
assert.deepEqual(results[3].relation, [3]);
assert.deepEqual(results[4].relation, [0, 4]);
for (let i = 0; i < results.length; i++) {
const r = results[i];
if (!r.independent) {
assert(r.relation.includes(i));
assert(r.relation.every(j => j <= i));
assert.equal(r.relation.reduce((x, j) => x ^ values[j], 0n), 0n);
}
}
assert.equal(b.size, 5);
assert.equal(b.rank, 2);
console.log('06 dependent relations verified');实际输出:
06 dependent relations verified
我们没有声称 relation 是最短关系,也没有声称 represent 返回的子集元素最少。只要数值和来源同步消元,就能保证正确性;寻找最少项的表示属于额外优化目标,不会从当前实现自动获得。向 AI 提需求时,最好把可行证据与最优证据明确拆开。
七、宽值与失败路径:不要只测三位玩具数据
小值容易让类型错误侥幸通过,因此这里补上一百三十位的合法输入,确保算法从未借助 Number 的位运算保存数据。入口只接受 BigInt,既不将字符串自动解析,也不把可能已经损失精度的 Number 转回来。若数据来自外部文本,应在独立的解析层验证格式,再按这个接口传入。
失败路径同样值得审:宽度错误应在构造时拒绝;负数、越界值、错误类型应在插入改变 size 或 rank 前拒绝;达到来源条目上限后也不能继续占用编号。下面验证的是这些预期的校验失败不会改变计数,不是对内存耗尽、进程中断等运行时故障承诺事务回滚。
示例 7:独立运行的 07.cjs。
'use strict';
const assert = require('node:assert/strict');
function makeCheck(width) {
if (!Number.isInteger(width) || width < 1 || width > 1024)
throw new RangeError('width must be 1..1024');
const limit = 1n << BigInt(width);
return value => {
if (typeof value !== 'bigint') throw new TypeError('BigInt required');
if (value < 0n || value >= limit) throw new RangeError('out of width');
return value;
};
}
class XorBasis {
#width; #check; #rows; #rank = 0; #size = 0;
constructor(width) {
this.#check = makeCheck(width);
this.#width = width;
this.#rows = Array(width).fill(null);
}
get rank() { return this.#rank; }
get size() { return this.#size; }
#indices(mask) {
const out = [];
for (let i = 0; mask !== 0n; i++, mask >>= 1n)
if ((mask & 1n) !== 0n) out.push(i);
return out;
}
insert(value) {
let x = this.#check(value);
if (this.#size >= 4096) throw new RangeError('item limit reached');
let mask = 1n << BigInt(this.#size++);
for (let i = this.#width - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
const row = this.#rows[i];
if (row) { x ^= row.value; mask ^= row.mask; }
else {
this.#rows[i] = { value: x, mask };
this.#rank++;
return { independent: true, relation: null };
}
}
return { independent: false, relation: this.#indices(mask) };
}
#reduce(value) {
let x = this.#check(value), mask = 0n;
for (let i = this.#width - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
const row = this.#rows[i];
if (!row) return { value: x, mask };
x ^= row.value; mask ^= row.mask;
}
return { value: x, mask };
}
has(value) { return this.#reduce(value).value === 0n; }
represent(value) {
const reduced = this.#reduce(value);
return reduced.value === 0n ? this.#indices(reduced.mask) : null;
}
maximizeXor(seed = 0n) {
let best = this.#check(seed), mask = 0n;
for (let i = this.#width - 1; i >= 0; i--) {
const row = this.#rows[i];
if (row && (best ^ row.value) > best) {
best ^= row.value; mask ^= row.mask;
}
}
return { value: best, indices: this.#indices(mask) };
}
}
for (const width of [0, -1, 1.5, NaN, Infinity, 1025, 3n])
assert.throws(() => new XorBasis(width), RangeError);
const b = new XorBasis(130);
const hi = 1n << 129n;
[hi, 5n].forEach(x => b.insert(x));
assert.equal(b.maximizeXor().value, hi ^ 5n);
assert.deepEqual(b.represent(hi ^ 5n), [0, 1]);
for (const value of [-1n, 1n << 130n]) {
assert.throws(() => b.insert(value), RangeError);
assert.throws(() => b.has(value), RangeError);
assert.throws(() => b.maximizeXor(value), RangeError);
}
assert.throws(() => b.insert(5), TypeError);
assert.equal(b.size, 2);
assert.equal(b.rank, 2);
const capped = new XorBasis(1);
for (let i = 0; i < 4096; i++) capped.insert(0n);
assert.throws(() => capped.insert(0n), RangeError);
assert.equal(capped.size, 4096);
assert.equal(capped.rank, 0);
console.log('07 wide values and rejection atomicity OK');实际输出:
07 wide values and rejection atomicity OK
四千零九十六条零输入都不增加秩,却仍消耗来源编号。这是为了保持第几次输入的含义清楚,并说明 rank 小不代表来源跟踪成本小。如果业务只需要成员判断或最大数值,可删除来源掩码和条目计数,使存储不再依赖输入条数;若需要删除历史元素或滑动窗口,则必须另外设计,当前结构仅支持追加。
八、穷举小域:用另一种算法核对全部结果
证明解释所有规模为什么成立,穷举检查实现是否忠实表达了证明,两者互补。我们把位宽固定为三,枚举长度零到四的全部有序输入数组,共四千六百八十一种;重复元素与零自然包含在内。每个数组都查询八个目标和八种初值,并在每个插入前缀检查独立性、秩计数与相关证据。
基准故意不使用消元。它从只含零的集合出发,每遇到一个输入,就把旧集合与旧集合逐项异或该输入后的集合合并,直接构造所有子集结果。这个指数规模做法适合极小数据,不用于生产大输入。和被测代码采用不同路线,有助于避免把同一个消元错误复制到测试答案里。
断言不止比较最大数值,还核对每个返回下标合法、没有重复、重新异或后确实得到目标;无解时必须为 null。插入是否独立则与插入前的可达集合交叉验证。由于子集结果可能重复,基准使用 Set,随后检查可达值数是否等于二的秩次方。这里的穷举范围写得很明确,不应宣传成对任意位宽的形式化验证。
示例 8:独立运行的 08.cjs。
'use strict';
const assert = require('node:assert/strict');
function makeCheck(width) {
if (!Number.isInteger(width) || width < 1 || width > 1024)
throw new RangeError('width must be 1..1024');
const limit = 1n << BigInt(width);
return value => {
if (typeof value !== 'bigint') throw new TypeError('BigInt required');
if (value < 0n || value >= limit) throw new RangeError('out of width');
return value;
};
}
class XorBasis {
#width; #check; #rows; #rank = 0; #size = 0;
constructor(width) {
this.#check = makeCheck(width);
this.#width = width;
this.#rows = Array(width).fill(null);
}
get rank() { return this.#rank; }
get size() { return this.#size; }
#indices(mask) {
const out = [];
for (let i = 0; mask !== 0n; i++, mask >>= 1n)
if ((mask & 1n) !== 0n) out.push(i);
return out;
}
insert(value) {
let x = this.#check(value);
if (this.#size >= 4096) throw new RangeError('item limit reached');
let mask = 1n << BigInt(this.#size++);
for (let i = this.#width - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
const row = this.#rows[i];
if (row) { x ^= row.value; mask ^= row.mask; }
else {
this.#rows[i] = { value: x, mask };
this.#rank++;
return { independent: true, relation: null };
}
}
return { independent: false, relation: this.#indices(mask) };
}
#reduce(value) {
let x = this.#check(value), mask = 0n;
for (let i = this.#width - 1; i >= 0; i--) {
if ((x & (1n << BigInt(i))) === 0n) continue;
const row = this.#rows[i];
if (!row) return { value: x, mask };
x ^= row.value; mask ^= row.mask;
}
return { value: x, mask };
}
has(value) { return this.#reduce(value).value === 0n; }
represent(value) {
const reduced = this.#reduce(value);
return reduced.value === 0n ? this.#indices(reduced.mask) : null;
}
maximizeXor(seed = 0n) {
let best = this.#check(seed), mask = 0n;
for (let i = this.#width - 1; i >= 0; i--) {
const row = this.#rows[i];
if (row && (best ^ row.value) > best) {
best ^= row.value; mask ^= row.mask;
}
}
return { value: best, indices: this.#indices(mask) };
}
}
function brute(values) {
let reachable = new Set([0n]);
for (const value of values)
reachable = new Set([...reachable, ...[...reachable].map(x => x ^ value)]);
return reachable;
}
function xorAt(values, indices, seed = 0n) {
assert.equal(new Set(indices).size, indices.length);
for (const i of indices) assert(Number.isInteger(i) && i >= 0 && i < values.length);
return indices.reduce((x, i) => x ^ values[i], seed);
}
let cases = 0;
function visit(values) {
cases++;
const b = new XorBasis(3);
let prefix = new Set([0n]);
values.forEach((v, i) => {
const result = b.insert(v);
assert.equal(result.independent, !prefix.has(v));
if (!result.independent) {
assert(result.relation.includes(i));
assert.equal(xorAt(values.slice(0, i + 1), result.relation), 0n);
}
prefix = brute(values.slice(0, i + 1));
assert.equal(BigInt(prefix.size), 1n << BigInt(b.rank));
});
const reachable = brute(values);
for (let t = 0n; t < 8n; t++) {
assert.equal(b.has(t), reachable.has(t));
const indices = b.represent(t);
if (reachable.has(t)) assert.equal(xorAt(values, indices), t);
else assert.equal(indices, null);
let expected = t;
for (const value of reachable) if ((t ^ value) > expected) expected = t ^ value;
const result = b.maximizeXor(t);
assert.equal(result.value, expected);
assert.equal(xorAt(values, result.indices, t), result.value);
}
if (values.length < 4)
for (let v = 0n; v < 8n; v++) visit([...values, v]);
}
visit([]);
assert.equal(cases, 4681);
console.log('08 exhaustive cases=4681, targets/seeds=37448');实际输出:
08 exhaustive cases=4681, targets/seeds=37448
运行输出中的三万七千四百四十八是数组与目标或初值的组合数,每一组合同时执行成员、见证和最大值检查。它不是随机测试次数,也不是性能指标。若以后修改类,优先保留这些性质测试,再增加业务特有约束和更宽数据的回归用例。
九、把 AI 评审意见变成可反驳的断言
最后给出三个极短反例,专门对付读起来顺口的错误评审意见。第一,输入去重后有三个数,不代表秩为三。第二,把全部输入异或得到零,不代表最大子集异或也是零。第三,给出一组合法下标,不代表它是最少元素的解:三和五能组合出六,直接选原始的六也行。
这是一种有用的协作方式:先让模型重述接口和不变量,再要求它为可能的错误主张寻找最小反例,最后把反例加入真实执行的断言。不要仅凭模型说已检查就接受结论,也不要拿一段措辞完整的证明替代运行代码。评审材料应同时交代合法输入、失败行为、返回值含义、可以核对的证据和明确的测试范围。
示例 9:独立运行的 09.cjs。
'use strict';
const assert = require('node:assert/strict');
function allXors(values) {
let out = new Set([0n]);
for (const value of values) {
const old = [...out];
for (const x of old) out.add(x ^ value);
}
return out;
}
// Three tempting AI-review claims, each with a small counterexample.
const values = [3n, 5n, 6n];
assert.equal(new Set(values).size, 3);
assert.equal(allXors(values).size, 4); // rank is 2, not 3
assert.equal(3n ^ 5n ^ 6n, 0n);
assert.equal([...allXors(values)].reduce((a, b) => a > b ? a : b), 6n);
const solutions = [];
for (let mask = 0; mask < 8; mask++) {
let x = 0n, count = 0;
for (let i = 0; i < 3; i++) if (mask & (1 << i)) { x ^= values[i]; count++; }
if (x === 6n) solutions.push(count);
}
assert.deepEqual(solutions.sort((a, b) => a - b), [1, 2]);
console.log('09 unique count, XOR-all, shortest-witness claims refuted');实际输出:
09 unique count, XOR-all, shortest-witness claims refuted
复杂度也应保持诚实。若把一次 BigInt 运算暂当作一个抽象操作,插入、成员和最大值的主元循环最多访问 W 个槽;构建 n 条输入最多进行 nW 级别的槽访问。但 BigInt 运算本身不是与位数无关的常数时间,来源掩码还可能长到 n 位,解码见证也会随最高来源编号增长。这里不据此许诺实际耗时,更不把该实现当作密码学常量时间代码。
若 r 是秩,保留的值和来源掩码可粗略按 rW 与 rn 个二进制位理解,另有 W 个槽的容器开销;这是数据表示层面的量级说明,不是 JavaScript 堆内存的精确字节数。前面的上限只是保护边界,仍需结合部署环境做资源评估。最终交付标准是契约一致、推导闭合、证据可重算、测试可复现,而不是让一个智能助手对另一个智能助手的答案表示赞同。

