AI 代码审查实战:JavaScript 最长严格递增子序列的重建、反例与穷举验证
AI 能很快写出一个带二分查找的最长递增子序列函数,但真正容易漏审的是接口和返回结果:重复值能否接续,负零怎么处理,返回的是边界数组还是实际下标链,以及所谓稳定结果究竟保证什么。本文把这些问题拆开,建立一条可以复制执行的 JavaScript 审查路径。
本文包含九个互相独立的完整示例。每段单独保存为 example.cjs 后,以 node --unhandled-rejections=strict example.cjs 运行,不需要第三方包,也不需要前文变量。全部输出在 Node.js v24.19.0 中核对;可查看 官方版本记录及 严格拒绝处理选项。该选项管理未处理的 Promise 拒绝,和每段代码开头的 JavaScript 严格模式不是同一件事。

一、先固定数据契约,别让隐式转换决定题意
最长严格递增子序列允许跳过元素,却不能改变原有先后顺序。这里的严格表示相邻选中值必须满足小于关系,因此三个相同的数只能贡献一个位置。本文只接收普通、稠密的数值数组,拒绝空洞与继承来的索引;元素必须是有限的 Number 原始值。字符串、布尔值、数字包装对象、BigInt、NaN 和正负无穷都不在接口内。空数组合法,答案长度为零。
校验后先建立快照,算法只读取快照,不排序、不覆盖调用者的数组。负零与正零按照数值大小属于同一档,快照统一把它们写成正零,返回 values 也使用正零;indices 始终指向原输入位置。这样显示层和序列化层不会出现符号零的不一致。普通小数与极大但有限的 Number 仍然合法,因为核心算法比较大小,不计算两数之差。
Number.isFinite 不会先把字符串转换成数字,其语义可直接核对 ECMAScript 官方规范。Object.hasOwn 用来区分自有索引和继承属性,见 对应规范条目。这里不承诺隔离恶意 Proxy 或带副作用的 getter;跨信任边界的输入应先解析成普通数据。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
const input = Object.freeze([-0, 2.5, -3]);
const copy = readNumbers(input);
assert.deepEqual(copy, [0, 2.5, -3]);
assert.ok(Object.is(input[0], -0));
assert.ok(Object.is(copy[0], 0));
const invalid = [null, new Float64Array([1]), [NaN], [Infinity],
[-Infinity], ["2"], [undefined], [null], [1n], [new Number(2)],
new Array(1)];
for (const bad of invalid) assert.throws(() => readNumbers(bad), TypeError);
const inherited = new Array(1);
Object.setPrototypeOf(inherited, { 0: 7 });
assert.throws(() => readNumbers(inherited), TypeError);
console.log("validation: 12 rejected; -0 normalized; input unchanged");运行输出:
validation: 12 rejected; -0 normalized; input unchanged
二、先写一个容易审计的平方级长度预言机
让 AI 同时生成高效实现和测试时,最容易出现的假安全是两份代码共享同一个错误。参考算法应采用不同的状态和转移方式:dp[i] 表示必须以当前位置结尾时的最长长度,枚举所有更早且值更小的位置,再把其中最大的长度加一。全局最大值就是答案,空输入单独由初始值零自然处理。
这份预言机需要平方级时间和线性空间,适合小规模对照,不适合直接拿来压测几十万个元素。它不依赖二分边界、末尾数组或者前驱指针,因此可以揭露高效实现把严格递增写成非递减、遗漏替换或者错误增长长度的问题。为避免另一个陷阱,代码没有通过展开运算把整个 dp 数组当成函数参数。
注意长度预言机只能证明最优长度,不能证明重建出的下标顺序合法,更不能裁定某一种同长答案应该被选中。审查时应将三个问题分开:长度是否最优、返回链是否真的是输入的子序列、选解行为是否符合公开契约。接下来的检查会分别提供证据,而不是用一个漂亮输出替代全部结论。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
function slowLength(input) {
const a = readNumbers(input);
const dp = new Array(a.length).fill(1);
let best = 0;
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < i; j++) {
if (a[j] < a[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
}
best = Math.max(best, dp[i]);
}
return best;
}
const cases = [[], [2, 2, 2], [3, 2, 1], [1, 2, 3],
[10, 9, 2, 5, 3, 7, 101, 18]];
const lengths = cases.map(slowLength);
assert.deepEqual(lengths, [0, 1, 1, 3, 4]);
console.log(JSON.stringify(lengths));运行输出:
[0,1,1,3,4]
三、理解二分状态,末尾数组不是最终答案
tails 的第 k 项表示扫描过的前缀中,长度为 k 加一的递增子序列能够取得的最小末尾值。它是一组不同长度的最优边界,不是一条共同的历史路径。新值到来时,查找第一个大于或等于它的位置:若找不到,就扩展长度;若找到,就用更小或相等的边界代表相同长度。
为什么使用大于或等于,而不是严格大于?因为相同的值不能互相接续。把二分条件从小于改成小于等于,就会把重复元素放到后一个槽位,悄悄换成最长非递减子序列。循环维护半开区间,区间左侧都小于目标,右侧都大于或等于目标;区间缩到一个位置时,那个位置才是需要的下界。
输入二、三、一是揭穿假重建的最小课堂案例之一。最终边界是一、三,但一在三后面,无法按这个顺序从原数组中取出。下面保留每轮边界快照,只用来解释状态。不要看到最终数组有序,就宣称它是合法答案;也不要用 indexOf 为这些数补下标,那会在重复值出现时制造新的歧义。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
function traceTails(input) {
const tails = [], trace = [];
for (const x of readNumbers(input)) {
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (tails[mid] < x) lo = mid + 1;
else hi = mid;
}
tails[lo] = x;
trace.push(tails.slice());
}
return trace;
}
const trace = traceTails([2, 3, 1]);
assert.deepEqual(trace, [[2], [2, 3], [1, 3]]);
console.log(JSON.stringify(trace));运行输出:
[[2],[2,3],[1,3]]
四、完整实现:保存原下标与不可回写的前驱
在 tails 之外,tailIndex 保存各长度当前代表的原始下标,prev 保存某个元素被选为代表时的前驱下标。新元素替换第 p 个槽位之前,先读取前一槽位的代表作为前驱。前驱一定来自更早的扫描位置,其值也严格更小,因此沿着指针回溯不会成环,而且相邻值满足题意。
本实现的确定性规则是:从左到右扫描;较小的末尾替换现有代表;相同末尾保留现有代表;每次写入只记录当时的前驱;最后从最长长度的当前代表回溯。旧节点的前驱不会随着某个槽位后来换人而修改。槽位代表可以变化,历史链接必须保持不变,这正是长度状态与重建状态之间的重要区别。
末尾边界保持严格递增,因为插入位置之前的值都小于新值,而之后的值大于旧边界、也就大于新值。较小末尾至少拥有与较大末尾同样多的后续延伸机会;配合前述前驱构造,每个已存在长度都有实际见证。整体时间为 O(n log n),快照、前驱与返回结果合计线性空间;回溯是迭代循环,不受递归调用栈深度限制。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
function lis(input) {
const a = readNumbers(input);
const tails = [], tailIndex = [];
const prev = new Array(a.length).fill(-1);
for (let i = 0; i < a.length; i++) {
const x = a[i];
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (tails[mid] < x) lo = mid + 1;
else hi = mid;
}
const p = lo;
if (p < tails.length && tails[p] === x) continue;
prev[i] = p === 0 ? -1 : tailIndex[p - 1];
tails[p] = x;
tailIndex[p] = i;
}
const indices = [];
let k = tails.length === 0 ? -1 : tailIndex[tails.length - 1];
while (k !== -1) {
indices.push(k);
k = prev[k];
}
indices.reverse();
return { length: indices.length, indices,
values: indices.map(i => a[i]) };
}
const r = lis([10, 9, 2, 5, 3, 7, 101, 18]);
assert.deepEqual(r, { length: 4, indices: [2, 4, 5, 7],
values: [2, 3, 7, 18] });
assert.deepEqual(lis([]), { length: 0, indices: [], values: [] });
console.log(JSON.stringify(r));运行输出:
{"length":4,"indices":[2,4,5,7],"values":[2,3,7,18]}五、确定性不等于字典序最小,也不等于下标最早
这一节是 AI 代码审查中最值得保留的反例。对于二、三、四、一、三、四,程序先建立二、三、四的链,后来一替换第一档;后面的三与四却与现有末尾相同,所以按照约定不替换。最终返回二、三、四,而输入还存在一、三、四这条同样长、数值字典序更小的链。
另一个输入二、一、三会返回下标一、二,但下标零、二同样是最优长度,且下标字典序更早。所以局部保留相等代表,并不能升级成全局最早下标保证。明确这些边界不会削弱算法的正确性:我们的目标本来就是稳定地返回一条最优链,稳定的含义是相同输入和相同实现给出相同结果。
若产品需要数值字典序最小、下标字典序最早,或者所有最优答案,必须把它当成新的输出规格,重新设计状态与证明。不能只在注释里补一句最优选解,也不能拿若干看起来顺眼的案例当成保证。下面将反例写为固定回归测试,未来修改相等值策略时会立即暴露对外行为变化。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
function lis(input) {
const a = readNumbers(input);
const tails = [], tailIndex = [];
const prev = new Array(a.length).fill(-1);
for (let i = 0; i < a.length; i++) {
const x = a[i];
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (tails[mid] < x) lo = mid + 1;
else hi = mid;
}
const p = lo;
if (p < tails.length && tails[p] === x) continue;
prev[i] = p === 0 ? -1 : tailIndex[p - 1];
tails[p] = x;
tailIndex[p] = i;
}
const indices = [];
let k = tails.length === 0 ? -1 : tailIndex[tails.length - 1];
while (k !== -1) {
indices.push(k);
k = prev[k];
}
indices.reverse();
return { length: indices.length, indices,
values: indices.map(i => a[i]) };
}
const tie = lis([2, 3, 4, 1, 3, 4]);
assert.deepEqual(tie.indices, [0, 1, 2]);
assert.deepEqual(tie.values, [2, 3, 4]);
const earlierAlternative = lis([2, 1, 3]);
assert.deepEqual(earlierAlternative.indices, [1, 2]);
assert.deepEqual(lis([5, 5, 5]).indices, [0]);
assert.deepEqual(lis([-0, 0, 1]),
{ length: 2, indices: [0, 2], values: [0, 1] });
assert.deepEqual(tie, lis([2, 3, 4, 1, 3, 4]));
console.log(JSON.stringify({ tie: tie.values,
chosenIndices: earlierAlternative.indices }));运行输出:
{"tie":[2,3,4],"chosenIndices":[1,2]}六、检查返回证据,而不是只检查长度字段
重建检查器接收原输入、候选结果和独立算出的最优长度。它逐项验证下标为整数、落在范围内、严格向右;验证每个值对应那个下标的规范化输入;再验证相邻值严格增加。最后还要让长度字段、下标数量和值数量三者一致。一个仅仅声称长度正确的对象,不能因此通过审查。
这里使用 Object.is 比较规范化后的值,是为了让负零策略也可执行地受到约束。如果输出偷偷保留负零,而契约要求正零,检查器会拒绝。普通数值比较对正负零不作严格大小区分,相关规则可查 Number 的小于比较定义。这是输入语义、算法顺序和展示策略三者应当一致的地方。
检查器并不要求候选值必须等于某一份参考重建,因为同长答案可能有多条。它只要求这条链合法并达到独立最优长度。为了保证检查器本身真的会拒绝错误,示例主动塞入倒序下标、重复下标、值与下标不一致、以及合法但过短的四种伪结果。测试工具也需要反向测试,不能只喂成功样本。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
function verifyResult(input, r, expectedLength) {
const a = readNumbers(input);
assert.ok(r && typeof r === "object");
assert.ok(Array.isArray(r.indices) && Array.isArray(r.values));
assert.equal(r.length, expectedLength);
assert.equal(r.indices.length, expectedLength);
assert.equal(r.values.length, expectedLength);
for (let p = 0; p < r.indices.length; p++) {
const i = r.indices[p];
assert.ok(Number.isInteger(i) && i >= 0 && i < a.length);
assert.ok(Object.is(r.values[p], a[i]));
if (p > 0) {
const j = r.indices[p - 1];
assert.ok(j < i, "indices must increase");
assert.ok(a[j] < a[i], "values must strictly increase");
}
}
return true;
}
const input = [2, 3, 1];
const good = { length: 2, indices: [0, 1], values: [2, 3] };
assert.equal(verifyResult(input, good, 2), true);
const bad = [
{ length: 2, indices: [2, 1], values: [1, 3] },
{ length: 2, indices: [0, 0], values: [2, 2] },
{ length: 2, indices: [0, 1], values: [1, 3] },
{ length: 1, indices: [0], values: [2] }
];
for (const r of bad) assert.throws(() => verifyResult(input, r, 2));
console.log("reconstruction: 1 accepted; 4 rejected");运行输出:
reconstruction: 1 accepted; 4 rejected
七、小域穷举:把每条最优下标链都列出来
穷举不只是多跑几个随机数。这里枚举取值域为负一、零、一,长度从零到七的全部三千二百八十个数组。针对每个输入,另一个递归过程枚举所有严格递增的下标选择,保存每条最长链的下标列表。它没有二分,也没有末尾状态,因而能够独立验证返回链确实属于该输入的最优解集合。
同一次检查还要求平方级预言机的长度与穷举长度一致,再用重建检查器验证返回对象。这种三方交叉比对比直接比较两份高效代码更有价值:一个检查边界长度,一个检查所有可能路径,一个检查输出结构。枚举包含空数组、大量重复、升降交错和同长多解,尤其适合发现隐藏在相等值附近的错误。
穷举的费用随长度指数增长,所以它被明确限制在短数组上;这不是生产算法的执行路径。测试范围完整,只意味着这个有限域内没有反例,不能夸大为对所有 Number 输入的形式化证明。真正的可信度来自清晰契约、不变量论证、独立算法和针对性实验共同支撑,而不是单个巨大的通过计数。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
function lis(input) {
const a = readNumbers(input);
const tails = [], tailIndex = [];
const prev = new Array(a.length).fill(-1);
for (let i = 0; i < a.length; i++) {
const x = a[i];
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (tails[mid] < x) lo = mid + 1;
else hi = mid;
}
const p = lo;
if (p < tails.length && tails[p] === x) continue;
prev[i] = p === 0 ? -1 : tailIndex[p - 1];
tails[p] = x;
tailIndex[p] = i;
}
const indices = [];
let k = tails.length === 0 ? -1 : tailIndex[tails.length - 1];
while (k !== -1) {
indices.push(k);
k = prev[k];
}
indices.reverse();
return { length: indices.length, indices,
values: indices.map(i => a[i]) };
}
function slowLength(input) {
const a = readNumbers(input);
const dp = new Array(a.length).fill(1);
let best = 0;
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < i; j++) {
if (a[j] < a[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
}
best = Math.max(best, dp[i]);
}
return best;
}
function verifyResult(input, r, expectedLength) {
const a = readNumbers(input);
assert.ok(r && typeof r === "object");
assert.ok(Array.isArray(r.indices) && Array.isArray(r.values));
assert.equal(r.length, expectedLength);
assert.equal(r.indices.length, expectedLength);
assert.equal(r.values.length, expectedLength);
for (let p = 0; p < r.indices.length; p++) {
const i = r.indices[p];
assert.ok(Number.isInteger(i) && i >= 0 && i < a.length);
assert.ok(Object.is(r.values[p], a[i]));
if (p > 0) {
const j = r.indices[p - 1];
assert.ok(j < i, "indices must increase");
assert.ok(a[j] < a[i], "values must strictly increase");
}
}
return true;
}
function exhaustiveOptimalIndices(a) {
let best = -1;
let answers = new Set();
function visit(i, chosen) {
if (i === a.length) {
if (chosen.length > best) {
best = chosen.length;
answers = new Set();
}
if (chosen.length === best) answers.add(JSON.stringify(chosen));
return;
}
visit(i + 1, chosen);
if (chosen.length === 0 || a[chosen[chosen.length - 1]] < a[i]) {
chosen.push(i);
visit(i + 1, chosen);
chosen.pop();
}
}
visit(0, []);
return { best, answers };
}
let checked = 0;
function check(a) {
const r = lis(a);
const brute = exhaustiveOptimalIndices(a);
const expected = slowLength(a);
assert.equal(expected, brute.best);
verifyResult(a, r, expected);
assert.ok(brute.answers.has(JSON.stringify(r.indices)));
assert.deepEqual(r, lis(a));
checked++;
}
function generate(a, remaining) {
if (remaining === 0) return check(a);
for (const x of [-1, 0, 1]) generate([...a, x], remaining - 1);
}
for (let n = 0; n <= 7; n++) generate([], n);
assert.equal(checked, 3280);
console.log("exhaustive arrays: " + checked);运行输出:
exhaustive arrays: 3280
八、补上有限浮点边界、可复现随机与大输入
小整数穷举很难覆盖 Number 的表现范围,因而还要直接加入最大有限值、最小正数、负数、小数和正负零。比较操作不会因为两个极值相减而溢出,因为实现没有做这种减法。相反,如果业务需要十进制金额或任意精度整数的精确顺序,必须先选择合适的数据表示,不能指望算法恢复输入阶段已经舍入掉的信息。
随机测试使用固定种子的简单发生器,目的只是让失败案例可以复现,不涉及密码学用途。每组数组都与平方级预言机比对,并检查输入未被修改。随后用两万项纯递增和纯递减数组做烟雾测试,验证长链的迭代回溯和代表不断替换时的行为;这些大输入直接使用数学上已知的答案,不再运行平方级预言机。
这里故意不写某台机器上的毫秒排行榜。计时受硬件、运行时预热和负载影响,单次结果不能证明渐近复杂度,也不应被包装成普遍性能承诺。若要给线上服务制定容量限制,应在实际部署环境里测量吞吐与内存,同时为输入长度建立业务上限;本文解决的是正确性证据和可重复审查流程。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
function lis(input) {
const a = readNumbers(input);
const tails = [], tailIndex = [];
const prev = new Array(a.length).fill(-1);
for (let i = 0; i < a.length; i++) {
const x = a[i];
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (tails[mid] < x) lo = mid + 1;
else hi = mid;
}
const p = lo;
if (p < tails.length && tails[p] === x) continue;
prev[i] = p === 0 ? -1 : tailIndex[p - 1];
tails[p] = x;
tailIndex[p] = i;
}
const indices = [];
let k = tails.length === 0 ? -1 : tailIndex[tails.length - 1];
while (k !== -1) {
indices.push(k);
k = prev[k];
}
indices.reverse();
return { length: indices.length, indices,
values: indices.map(i => a[i]) };
}
function slowLength(input) {
const a = readNumbers(input);
const dp = new Array(a.length).fill(1);
let best = 0;
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < i; j++) {
if (a[j] < a[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
}
best = Math.max(best, dp[i]);
}
return best;
}
function verifyResult(input, r, expectedLength) {
const a = readNumbers(input);
assert.ok(r && typeof r === "object");
assert.ok(Array.isArray(r.indices) && Array.isArray(r.values));
assert.equal(r.length, expectedLength);
assert.equal(r.indices.length, expectedLength);
assert.equal(r.values.length, expectedLength);
for (let p = 0; p < r.indices.length; p++) {
const i = r.indices[p];
assert.ok(Number.isInteger(i) && i >= 0 && i < a.length);
assert.ok(Object.is(r.values[p], a[i]));
if (p > 0) {
const j = r.indices[p - 1];
assert.ok(j < i, "indices must increase");
assert.ok(a[j] < a[i], "values must strictly increase");
}
}
return true;
}
let state = 20261019;
function next() {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
return state;
}
const pool = [-Number.MAX_VALUE, -10, -0.1, -Number.MIN_VALUE,
-0, 0, Number.MIN_VALUE, 0.1, 10, Number.MAX_VALUE];
for (let t = 0; t < 500; t++) {
const a = Array.from({ length: next() % 41 }, () => pool[next() % pool.length]);
const before = a.slice();
verifyResult(a, lis(a), slowLength(a));
assert.deepEqual(a, before);
}
const increasing = Array.from({ length: 20000 }, (_, i) => i);
const decreasing = increasing.slice().reverse();
verifyResult(increasing, lis(increasing), 20000);
verifyResult(decreasing, lis(decreasing), 1);
assert.deepEqual(lis(decreasing).indices, [19999]);
assert.deepEqual(lis([-Number.MAX_VALUE, Number.MAX_VALUE]).values,
[-Number.MAX_VALUE, Number.MAX_VALUE]);
console.log("seeded cases: 500; large cases: 2; finite extremes: passed");运行输出:
seeded cases: 500; large cases: 2; finite extremes: passed
九、给测试做一次破坏实验,再决定能否合并
最后主动放入两个典型缺陷,确认测试真的能把它们抓住。第一个把二分中的严格小于改成小于等于,让三个七错误地得到长度三。第二个把末尾状态一、三伪装成输入二、三、一的实际答案,虽然长度仍然正确,却没有合法的原始顺序。前者需要长度预言机,后者需要重建检查器,缺一不可。
让 AI 修改实现之前,可以先要求它给出输入契约、状态含义、循环不变量、确定性选择规则和可能的反例;修改之后再要求独立测试,而不是让它复述自己刚写的解释。对于看似合理的高级承诺,尤其是字典序最小和稳定选解,应要求可执行反例搜索或者完整证明。文字自信不是算法性质,测试通过也不是所有性质同时成立。
合并前应逐项确认:所有输入校验路径可触达,重复值不能增加长度,负零输出已规范化,输入没有被排序或写回,旧前驱不被更新,空输入可返回空链,最优长度有独立依据,重建链的下标与数值都合法。保留失败反例和种子,并在后续重构时重复运行,才能让这次审查的价值持续存在。
"use strict";
const assert = require("node:assert/strict");
function readNumbers(input) {
if (!Array.isArray(input)) throw new TypeError("expected Array");
const n = input.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
if (!Object.hasOwn(input, i)) throw new TypeError("hole at " + i);
const x = input[i];
if (!Number.isFinite(x)) throw new TypeError("invalid number at " + i);
a[i] = x === 0 ? 0 : x;
}
return a;
}
function slowLength(input) {
const a = readNumbers(input);
const dp = new Array(a.length).fill(1);
let best = 0;
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < i; j++) {
if (a[j] < a[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
}
best = Math.max(best, dp[i]);
}
return best;
}
function verifyResult(input, r, expectedLength) {
const a = readNumbers(input);
assert.ok(r && typeof r === "object");
assert.ok(Array.isArray(r.indices) && Array.isArray(r.values));
assert.equal(r.length, expectedLength);
assert.equal(r.indices.length, expectedLength);
assert.equal(r.values.length, expectedLength);
for (let p = 0; p < r.indices.length; p++) {
const i = r.indices[p];
assert.ok(Number.isInteger(i) && i >= 0 && i < a.length);
assert.ok(Object.is(r.values[p], a[i]));
if (p > 0) {
const j = r.indices[p - 1];
assert.ok(j < i, "indices must increase");
assert.ok(a[j] < a[i], "values must strictly increase");
}
}
return true;
}
function wrongNonDecreasingLength(input) {
const tails = [];
for (const x of readNumbers(input)) {
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (tails[mid] <= x) lo = mid + 1;
else hi = mid;
}
tails[lo] = x;
}
return tails.length;
}
const duplicate = [7, 7, 7];
assert.equal(slowLength(duplicate), 1);
assert.equal(wrongNonDecreasingLength(duplicate), 3);
assert.notEqual(wrongNonDecreasingLength(duplicate), slowLength(duplicate));
const wrongTailsAsAnswer = { length: 2, indices: [2, 1], values: [1, 3] };
assert.throws(() => verifyResult([2, 3, 1], wrongTailsAsAnswer, 2));
console.log("caught mutants: non-strict comparison; tails-as-reconstruction");运行输出:
caught mutants: non-strict comparison; tails-as-reconstruction

