AI 代码审查实践:用 JavaScript 实现可验证的二维 k-d 树最近邻查询

10-20 5阅读

让 AI 写一棵 k-d 树并不难,难的是判断那段看起来像教科书的代码,在整数很大、多个点重合、距离相等时是否仍然可靠。最近邻查询尤其容易制造一种错觉:只要沿着分割线向下走,找到的点似乎就应该最近;只要树是平衡的,查询似乎就应该是对数时间。这两句话都不足以成为正确性保证。

本文把 AI 当作可被质疑的代码协作者,围绕一个明确任务展开审查:对一批静态二维整数点建树,随后查询离给定坐标最近的一个点;距离相同时,以字符串 ID 的确定性顺序决定唯一答案。我们不做动态插入、不做近似搜索,也不把问题偷换成寻找点集中距离最近的一对点。前者需要处理更新,后者的输入与输出都不同。

这里的原理依据是普林斯顿大学的 Kd-Trees 课程作业:用矩形提供距离下界,只有不能排除更好答案的子树才值得继续搜索。本文自行实现中位数静态建树和子树紧包围盒,并额外处理精确整数与等距 ID。数值语义参照 ECMAScript 2025 的 BigInt 定义;代码、测试数据和审查过程均为本文独立设计。

AI 代码审查实践:用 JavaScript 实现可验证的二维 k-d 树最近邻查询
AI 生成的概念插图:矩形表示空间分组,亮色路径表示搜索意象。画面不是实际运行轨迹,也不用于证明距离关系。

以下九段程序都可以单独保存为对应的 .cjs 文件,使用 Node.js 执行,例如 node 01.cjs。它们只使用运行时自带的断言模块,不需要安装依赖,也不依赖前一段程序留下的变量。为了保证复制后即可运行,后几段会重复完整实现。文中输出已在 Node.js v24.19.0 实际核对;每段代码后面的普通文本框就是对应标准输出。

先给 AI 一份可以验收的约定

审查开始前,先把口头需求收紧成接口约定。输入是普通、无副作用的点对象组成的稠密数组,每个对象有非空且全局唯一的字符串 id,以及 bigint 类型的 x、y。重复坐标合法,重复 ID 非法。查询点同样必须提供两个 bigint 坐标;空树返回 null,非空树返回包含 id 和精确平方距离 d2 的对象。数据只建一次,之后不原地修改索引。

这里的 ID 次序使用 JavaScript 字符串关系运算,按 UTF-16 码元比较,区分大小写,不做本地化排序或 Unicode 归一化。因此字符串 10 可以排在 2 前面。如果业务想按数值编号或人类姓名排序,应先修改契约,再同时修改候选比较、建树次序和测试预期,不能只在某一处换成 localeCompare。

可以把审查请求写得具体一些:请指出所有依赖输入范围的假设;给出剪枝不漏解的理由;分别构造大整数、重复点、等距点的反例;用独立暴力扫描对照全部输出;最后解释复杂度中哪些结论来自树高,哪些来自数据分布。这样的提问会把 AI 的工作从修饰代码,转向提供可被运行和推翻的证据。

一、先审数值:平方距离也可能丢失精度

第一个示例故意让两个相邻的大整数先经过 Number。转换后差值变成零,这不是平方运算造成的,而是坐标在入口已经失去信息。再把这个 Number 转回 BigInt,也找不回被舍弃的那一位。因此本实现要求调用方直接提供 bigint;如果来源是 JSON,应把整数坐标编码成十进制字符串,在校验格式后直接交给 BigInt,而不是先经过 Number。

即使每个坐标单独处于安全整数范围,两个坐标之差的平方仍可能超出该范围。最近邻只需要比较距离,不需要展示开方后的近似值,所以全过程保留平方距离。两个差值、乘法、加法和包围盒下界都使用 BigInt,避免中途悄悄回到浮点数。示例还检查 Number 与 BigInt 混合算术会抛错,提醒审查者留意把零写成 0n。

精确并不等于没有成本。BigInt 的位数可以增长,乘法和比较也会随位宽变化;后文的节点访问复杂度不能被解释成每个节点消耗恒定的真实时间。对不可信的超长输入,服务端还应限制数字长度、点数和查询次数,这属于资源治理,不能寄希望于数据结构自动解决。

独立示例 01:保存为 01.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
const a = BigInt("9007199254740992");
const b = BigInt("9007199254740993");
console.log("Number gap:", Number(b) - Number(a));
console.log("BigInt squared gap:", ((b - a) ** 2n).toString());
const h = 9007199254740991n;
const d2 = (h - (-h)) ** 2n + (h - (-h)) ** 2n;
assert.equal(d2, 8n * h * h);
console.log("opposite corners:", d2.toString());
assert.throws(() => 1n + 1, TypeError);
console.log("mixed arithmetic rejected");

运行输出:

Number gap: 0
BigInt squared gap: 1
opposite corners: 649037107316853309451123965296648
mixed arithmetic rejected

二、先写暴力答案,再讨论树

在优化实现之前,先写一个线性扫描作为裁判。它完全不接触树、包围盒或剪枝条件,只逐个计算平方距离,然后用同一份业务契约打破平局。示例里 z 与 a 距离查询点都为一,答案必须是 a,而不是先看到谁就返回谁。空数组也有明确返回值,调用者不必解析一个带 Infinity 的伪答案。

这段代码还有一个 JavaScript 专属陷阱:数组排序比较器不能直接返回两个 BigInt 的差。排序算法会把比较结果按 Number 处理,BigInt 结果会触发类型错误。正确做法是通过关系判断返回普通的负一、零或一。相关转换步骤可以直接核对 规范中的 CompareArrayElements,比让 AI 猜测某个引擎会不会接受更可靠。

暴力程序不是形式化证明,也可能写错,所以这里让它使用单独的距离表达式和更新逻辑,不复用优化实现中的距离函数或候选辅助函数。后面还会用手工可知答案的案例校验两者。独立性是相对的:二者仍共享接口约定,但至少不会因为调用同一个错误的剪枝函数而一起给出漂亮的假通过。

独立示例 02:保存为 02.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
function brute(points, q) {
  let answer = null;
  for (const p of points) {
    const a = p.x - q.x, b = p.y - q.y;
    const distance = a ** 2n + b ** 2n;
    if (answer === null || distance < answer.d2 ||
        (distance === answer.d2 && p.id < answer.id))
      answer = { id: p.id, d2: distance };
  }
  return answer;
}
const points = [
  { id: "z", x: -1n, y: 0n },
  { id: "a", x: 1n, y: 0n }
];
const hit = brute(points, { x: 0n, y: 0n });
assert.deepEqual(hit, { id: "a", d2: 1n });
assert.equal(brute([], { x: 0n, y: 0n }), null);
assert.throws(() => [2n, 1n].sort((a, b) => a - b), TypeError);
console.log("winner:", hit.id, hit.d2.toString());
console.log("empty:", brute([], { x: 0n, y: 0n }));
console.log("BigInt sort comparator rejected");

运行输出:

winner: a 1
empty: null
BigInt sort comparator rejected

三、证明包围盒下界,而不是凭图猜

一个节点的包围盒记录该子树所有点的最小和最大横纵坐标。对于查询点,先分别计算它到两个闭区间的距离:落在区间内就是零;在左侧取左端点减查询坐标;在右侧取查询坐标减右端点。把横纵两个距离平方后相加,就得到查询点到矩形的最小平方距离。

为什么它能用于剪枝?子树中每个点的横坐标都在横向区间内,所以它的横向距离不小于上述最小距离;纵向也一样。两项都是非负数,平方后再相加仍保持这个下界关系。这一推导不依赖浮点容差,也不要求最近点恰好落在矩形角上。查询点在矩形内部或边界上时,下界为零,但并不说明子树里真的存在零距离点。

示例分别覆盖内部、角点、边外和角外四种位置,并检查矩形内二十个整数点对每个查询都满足下界关系。这里有八十次检查,而不是八十个随机样本。真实查询不用枚举矩形内的点;枚举只是帮助我们单独验证这个小而关键的组件,避免把边界错误藏到整棵树的输出里。

独立示例 03:保存为 03.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
function pointD2(p, q) {
  const dx = p.x - q.x, dy = p.y - q.y;
  return dx * dx + dy * dy;
}
function boxD2(b, q) {
  const dx = q.x < b.minX ? b.minX - q.x :
    q.x > b.maxX ? q.x - b.maxX : 0n;
  const dy = q.y < b.minY ? b.minY - q.y :
    q.y > b.maxY ? q.y - b.maxY : 0n;
  return dx * dx + dy * dy;
}
const box = { minX: 1n, maxX: 4n, minY: 2n, maxY: 6n };
const queries = [
  { x: 2n, y: 3n }, { x: 4n, y: 6n },
  { x: 7n, y: 3n }, { x: -1n, y: -2n }
];
const distances = queries.map(q => boxD2(box, q));
assert.deepEqual(distances, [0n, 0n, 9n, 20n]);
for (const q of queries)
  for (let x = 1n; x <= 4n; x++)
    for (let y = 2n; y <= 6n; y++)
      assert.ok(boxD2(box, q) <= pointD2({ x, y }, q));
console.log("box lower bounds:", distances.map(String).join(", "));
console.log("all 80 lower-bound checks passed");

运行输出:

box lower bounds: 0, 0, 9, 20
all 80 lower-bound checks passed

四、建一棵确定且不会被调用方改坏的静态树

建树按深度交替选择横轴和纵轴,在当前轴排序后取中位数作为节点。当前轴相同,再比较另一轴,最后比较唯一 ID,形成完整的确定次序。这能保证同一组点无论输入排列如何,都会形成相同的树;重复坐标也不会破坏划分,因为按排序下标分成两半,左右点数至多差一。

这里使用的是子树点集的紧包围盒,而不是从无限平面继承下来的分割区域。每次先建立左右子树,再把两个孩子的范围与当前点合并,得到真实包含所有子孙的矩形。坐标相等时,左右子树的矩形可以相接或重叠,这不影响下界正确性。不要额外假设左边的所有横坐标都严格更小,否则重复坐标会成为隐蔽反例。

输入点会被复制并冻结,节点也被冻结,排序只作用于内部新数组。这样调用方后来修改原对象,不会出现点已经移动而包围盒仍停留在旧位置的问题。示例检查子树包含关系、节点数量平衡、冻结状态、反转输入后的树结构,并实际修改原数组里的坐标来核验快照行为。冻结不是通用安全沙箱,此接口仍面向普通可信数据对象,而不是带恶意 getter 的对象图。

独立示例 04:保存为 04.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function checkXY(p) {
  if (!p || typeof p.x !== "bigint" || typeof p.y !== "bigint")
    throw new TypeError("x and y must be BigInt");
}
function copyPoints(input) {
  if (!Array.isArray(input)) throw new TypeError("points must be an array");
  const ids = new Set();
  return Array.from(input, p => {
    checkXY(p);
    if (typeof p.id !== "string" || p.id.length === 0 || ids.has(p.id))
      throw new TypeError("ids must be nonempty unique strings");
    ids.add(p.id);
    return Object.freeze({ id: p.id, x: p.x, y: p.y });
  });
}
function build(input) {
  function rec(a, depth) {
    if (a.length === 0) return null;
    const axis = depth % 2 === 0 ? "x" : "y";
    const other = axis === "x" ? "y" : "x";
    a.sort((p, q) => cmp(p[axis], q[axis]) ||
      cmp(p[other], q[other]) || cmp(p.id, q.id));
    const m = Math.floor(a.length / 2), p = a[m];
    const left = rec(a.slice(0, m), depth + 1);
    const right = rec(a.slice(m + 1), depth + 1);
    let minX = p.x, maxX = p.x, minY = p.y, maxY = p.y;
    for (const c of [left, right]) if (c) {
      if (c.minX < minX) minX = c.minX;
      if (c.maxX > maxX) maxX = c.maxX;
      if (c.minY < minY) minY = c.minY;
      if (c.maxY > maxY) maxY = c.maxY;
    }
    return Object.freeze({ p, left, right, minX, maxX, minY, maxY });
  }
  return rec(copyPoints(input), 0);
}
const points = [
  { id: "d", x: 2n, y: 2n }, { id: "a", x: 0n, y: 0n },
  { id: "c", x: 2n, y: 0n }, { id: "b", x: 0n, y: 2n }
];
const root = build(points);
function audit(n) {
  if (!n) return { points: [], height: 0 };
  const l = audit(n.left), r = audit(n.right);
  const all = [n.p, ...l.points, ...r.points];
  for (const p of all) {
    assert.ok(n.minX <= p.x && p.x <= n.maxX);
    assert.ok(n.minY <= p.y && p.y <= n.maxY);
  }
  assert.ok(Math.abs(l.points.length - r.points.length) <= 1);
  assert.ok(Object.isFrozen(n) && Object.isFrozen(n.p));
  return { points: all, height: 1 + Math.max(l.height, r.height) };
}
const report = audit(root);
assert.deepEqual(root, build([...points].reverse()));
points[0].x = 999n;
assert.equal(root.maxX, 2n);
console.log("root:", root.p.id);
console.log("nodes:", report.points.length, "height:", report.height);
console.log("snapshot and reversed input passed");

运行输出:

root: c
nodes: 4 height: 3
snapshot and reversed input passed

五、把最近邻查询写成可以解释的分支限界

查询维护当前最优候选 best。访问节点前,如果已有候选,而且该节点包围盒的距离下界严格大于当前最优平方距离,那么整个子树都不可能提供更好答案,可以直接跳过。否则必须先检查当前节点的点,再递归考虑子树。注意比较是严格大于:下界相等时,子树仍可能含有同距离但 ID 更小的点。

搜索顺序也有意义。代码比较左右孩子的包围盒下界,优先探索更近的那个,希望尽早缩小最优距离。但这只影响效率,不能改变最终答案。探索第二个孩子时,必须使用第一个孩子搜索结束后的最新 best 重新判断,不能沿用进入父节点时缓存的旧半径。示例的 visit 在每次入口重新检查,避免状态更新被遗漏。

正确性可以分成三句话:没有被剪掉的节点,其点都会参与候选比较;被剪掉的子树,其所有点距离都严格大于已经发现的候选;候选始终保存已见点中距离优先、ID 次优先的最小项。遍历结束后,不可能再有遗漏的更优点。不要因为命中零距离就提前结束,除非还能证明剩余点的 ID 都不可能胜出。

下面是完整查询实现。stats.visited 统计真正计算点距离的节点数,stats.pruned 统计被跳过的子树入口数,两者不是同一种单位,不能相加当作总点数。这个小数据集里根节点恰好就是最近点,两个孩子都能被排除;它只是可复现的运行示例,不能拿来宣传普遍加速比例。

独立示例 05:保存为 05.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function checkXY(p) {
  if (!p || typeof p.x !== "bigint" || typeof p.y !== "bigint")
    throw new TypeError("x and y must be BigInt");
}
function copyPoints(input) {
  if (!Array.isArray(input)) throw new TypeError("points must be an array");
  const ids = new Set();
  return Array.from(input, p => {
    checkXY(p);
    if (typeof p.id !== "string" || p.id.length === 0 || ids.has(p.id))
      throw new TypeError("ids must be nonempty unique strings");
    ids.add(p.id);
    return Object.freeze({ id: p.id, x: p.x, y: p.y });
  });
}
function build(input) {
  function rec(a, depth) {
    if (a.length === 0) return null;
    const axis = depth % 2 === 0 ? "x" : "y";
    const other = axis === "x" ? "y" : "x";
    a.sort((p, q) => cmp(p[axis], q[axis]) ||
      cmp(p[other], q[other]) || cmp(p.id, q.id));
    const m = Math.floor(a.length / 2), p = a[m];
    const left = rec(a.slice(0, m), depth + 1);
    const right = rec(a.slice(m + 1), depth + 1);
    let minX = p.x, maxX = p.x, minY = p.y, maxY = p.y;
    for (const c of [left, right]) if (c) {
      if (c.minX < minX) minX = c.minX;
      if (c.maxX > maxX) maxX = c.maxX;
      if (c.minY < minY) minY = c.minY;
      if (c.maxY > maxY) maxY = c.maxY;
    }
    return Object.freeze({ p, left, right, minX, maxX, minY, maxY });
  }
  return rec(copyPoints(input), 0);
}
function pointD2(p, q) {
  const dx = p.x - q.x, dy = p.y - q.y;
  return dx * dx + dy * dy;
}
function boxD2(b, q) {
  const dx = q.x < b.minX ? b.minX - q.x :
    q.x > b.maxX ? q.x - b.maxX : 0n;
  const dy = q.y < b.minY ? b.minY - q.y :
    q.y > b.maxY ? q.y - b.maxY : 0n;
  return dx * dx + dy * dy;
}
function nearest(root, q, stats = {}) {
  checkXY(q);
  stats.visited = 0; stats.pruned = 0;
  let best = null;
  function visit(n) {
    if (!n) return;
    // Equality must remain searchable: a smaller id may still win.
    if (best && boxD2(n, q) > best.d2) { stats.pruned++; return; }
    stats.visited++;
    const d2 = pointD2(n.p, q);
    if (!best || d2 < best.d2 || (d2 === best.d2 && n.p.id < best.id))
      best = { id: n.p.id, d2 };
    let first = n.left, second = n.right;
    if (first && second && boxD2(first, q) > boxD2(second, q))
      [first, second] = [second, first];
    visit(first);
    visit(second); // Recheck its bound against the UPDATED best.
  }
  visit(root);
  return best;
}
const points = [
  { id: "A", x: 0n, y: 0n }, { id: "B", x: 4n, y: 0n },
  { id: "C", x: 4n, y: 5n }, { id: "D", x: -8n, y: 9n }
];
const tree = build(points), stats = {};
const hit = nearest(tree, { x: 3n, y: 1n }, stats);
assert.deepEqual(hit, { id: "B", d2: 2n });
console.log("nearest:", hit.id, "squared distance:", hit.d2.toString());
console.log("visited:", stats.visited, "pruned subtrees:", stats.pruned);
console.log("empty:", nearest(build([]), { x: 0n, y: 0n }));

运行输出:

nearest: B squared distance: 2
visited: 1 pruned subtrees: 2
empty: null

六、用针对性反例追问 AI 的边界判断

这一节专门验证最容易被一句看起来合理的优化破坏的性质。第一组是相同坐标、不同 ID,第二组是分居两侧的等距点;两组都要求返回 a。中位数建树可能先看到其他 ID,因而它们能揭露把严格大于误改成大于等于,以及零距离立即返回的错误。再把输入顺序反转,检查答案和树形都不随偶然排列变化。

后两组用十的八十次方构造尺度极大的坐标,既有相邻整数,也有正负两端。测试同时查询原点和巨大坐标附近的位置,把大跨度与近距离放在同一套运算里。如果某个 AI 版本在某一步调用 Number,或者用 Math.sqrt 再比较,应该先要求它解释为什么不会丢失这里的差异,而不是凭通常够用放行。

错误输入也要检查:Number 坐标、重复 ID、空 ID 和不合法查询必须明确抛错,包括空树上的不合法查询。拒绝规则是接口的一部分,不能因为没有数据就绕过。当前测试不声称覆盖所有可能的 JavaScript 对象行为,它覆盖的是开头约定的输入空间和最重要的拒绝分支。

独立示例 06:保存为 06.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function checkXY(p) {
  if (!p || typeof p.x !== "bigint" || typeof p.y !== "bigint")
    throw new TypeError("x and y must be BigInt");
}
function copyPoints(input) {
  if (!Array.isArray(input)) throw new TypeError("points must be an array");
  const ids = new Set();
  return Array.from(input, p => {
    checkXY(p);
    if (typeof p.id !== "string" || p.id.length === 0 || ids.has(p.id))
      throw new TypeError("ids must be nonempty unique strings");
    ids.add(p.id);
    return Object.freeze({ id: p.id, x: p.x, y: p.y });
  });
}
function build(input) {
  function rec(a, depth) {
    if (a.length === 0) return null;
    const axis = depth % 2 === 0 ? "x" : "y";
    const other = axis === "x" ? "y" : "x";
    a.sort((p, q) => cmp(p[axis], q[axis]) ||
      cmp(p[other], q[other]) || cmp(p.id, q.id));
    const m = Math.floor(a.length / 2), p = a[m];
    const left = rec(a.slice(0, m), depth + 1);
    const right = rec(a.slice(m + 1), depth + 1);
    let minX = p.x, maxX = p.x, minY = p.y, maxY = p.y;
    for (const c of [left, right]) if (c) {
      if (c.minX < minX) minX = c.minX;
      if (c.maxX > maxX) maxX = c.maxX;
      if (c.minY < minY) minY = c.minY;
      if (c.maxY > maxY) maxY = c.maxY;
    }
    return Object.freeze({ p, left, right, minX, maxX, minY, maxY });
  }
  return rec(copyPoints(input), 0);
}
function pointD2(p, q) {
  const dx = p.x - q.x, dy = p.y - q.y;
  return dx * dx + dy * dy;
}
function boxD2(b, q) {
  const dx = q.x < b.minX ? b.minX - q.x :
    q.x > b.maxX ? q.x - b.maxX : 0n;
  const dy = q.y < b.minY ? b.minY - q.y :
    q.y > b.maxY ? q.y - b.maxY : 0n;
  return dx * dx + dy * dy;
}
function nearest(root, q, stats = {}) {
  checkXY(q);
  stats.visited = 0; stats.pruned = 0;
  let best = null;
  function visit(n) {
    if (!n) return;
    // Equality must remain searchable: a smaller id may still win.
    if (best && boxD2(n, q) > best.d2) { stats.pruned++; return; }
    stats.visited++;
    const d2 = pointD2(n.p, q);
    if (!best || d2 < best.d2 || (d2 === best.d2 && n.p.id < best.id))
      best = { id: n.p.id, d2 };
    let first = n.left, second = n.right;
    if (first && second && boxD2(first, q) > boxD2(second, q))
      [first, second] = [second, first];
    visit(first);
    visit(second); // Recheck its bound against the UPDATED best.
  }
  visit(root);
  return best;
}
function brute(points, q) {
  let answer = null;
  for (const p of points) {
    const a = p.x - q.x, b = p.y - q.y;
    const distance = a ** 2n + b ** 2n;
    if (answer === null || distance < answer.d2 ||
        (distance === answer.d2 && p.id < answer.id))
      answer = { id: p.id, d2: distance };
  }
  return answer;
}
const origin = { x: 0n, y: 0n }, huge = 10n ** 80n;
const cases = [
  [{ id: "z", x: 0n, y: 0n }, { id: "a", x: 0n, y: 0n }],
  [{ id: "z", x: -1n, y: 0n }, { id: "a", x: 1n, y: 0n }],
  [{ id: "A", x: huge, y: huge }, { id: "B", x: huge + 1n, y: huge }],
  [{ id: "L", x: -huge, y: -huge }, { id: "R", x: huge, y: huge }]
];
for (const points of cases) {
  const tree = build(points);
  for (const q of [origin, { x: huge, y: huge + 1n }])
    assert.deepEqual(nearest(tree, q), brute(points, q));
  assert.deepEqual(tree, build([...points].reverse()));
}
assert.equal(nearest(build(cases[0]), origin).id, "a");
assert.equal(nearest(build(cases[1]), origin).id, "a");
assert.throws(() => build([{ id: "x", x: 1, y: 2n }]), TypeError);
assert.throws(() => build([
  { id: "x", x: 1n, y: 2n }, { id: "x", x: 3n, y: 4n }
]), TypeError);
assert.throws(() => build([{ id: "", x: 1n, y: 2n }]), TypeError);
assert.throws(() => nearest(null, { x: 0, y: 0n }), TypeError);
console.log("duplicate coordinates, equal distances, 10^80-scale extremes: passed");
console.log("invalid types and duplicate ids: rejected");

运行输出:

duplicate coordinates, equal distances, 10^80-scale extremes: passed
invalid types and duplicate ids: rejected

七、对小世界穷举,让错误无处躲藏

随机测试常常很有用,但某些对称关系出现的概率并不高。这里先把世界缩小:用横纵坐标均属于负一、零、一的九个点构成候选集,穷举它的全部五百一十二个子集;再用横纵坐标属于负二到二的二十五个查询点逐一查询。每个子集分别以原顺序和反顺序建树,合计二万五千六百次树查询与暴力结果比较。

这一设计自然覆盖空集、单点、共线、对称、边界、远离数据区域等情况,同时比较 ID 和 BigInt 距离,而不是只比较一个近似距离值。小世界穷举不包含重复坐标,因为候选网格点本来不同,所以不能替代上一节的重复点测试。审查报告必须写清楚覆盖边界,避免把穷举这个词包装成对所有整数输入的保证。

一旦比较失败,最有价值的输出是子集掩码、查询坐标和两个答案,而不是继续跑更多数据。这段短程序直接使用断言中止;在日常工程里,可以在断言外包一层失败记录,把案例保存为十进制字符串形式,再最小化为下一次固定回归测试。这样 AI 的修复必须通过原始失败案例,不能只靠重新生成一批随机数获得通过。

独立示例 07:保存为 07.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function checkXY(p) {
  if (!p || typeof p.x !== "bigint" || typeof p.y !== "bigint")
    throw new TypeError("x and y must be BigInt");
}
function copyPoints(input) {
  if (!Array.isArray(input)) throw new TypeError("points must be an array");
  const ids = new Set();
  return Array.from(input, p => {
    checkXY(p);
    if (typeof p.id !== "string" || p.id.length === 0 || ids.has(p.id))
      throw new TypeError("ids must be nonempty unique strings");
    ids.add(p.id);
    return Object.freeze({ id: p.id, x: p.x, y: p.y });
  });
}
function build(input) {
  function rec(a, depth) {
    if (a.length === 0) return null;
    const axis = depth % 2 === 0 ? "x" : "y";
    const other = axis === "x" ? "y" : "x";
    a.sort((p, q) => cmp(p[axis], q[axis]) ||
      cmp(p[other], q[other]) || cmp(p.id, q.id));
    const m = Math.floor(a.length / 2), p = a[m];
    const left = rec(a.slice(0, m), depth + 1);
    const right = rec(a.slice(m + 1), depth + 1);
    let minX = p.x, maxX = p.x, minY = p.y, maxY = p.y;
    for (const c of [left, right]) if (c) {
      if (c.minX < minX) minX = c.minX;
      if (c.maxX > maxX) maxX = c.maxX;
      if (c.minY < minY) minY = c.minY;
      if (c.maxY > maxY) maxY = c.maxY;
    }
    return Object.freeze({ p, left, right, minX, maxX, minY, maxY });
  }
  return rec(copyPoints(input), 0);
}
function pointD2(p, q) {
  const dx = p.x - q.x, dy = p.y - q.y;
  return dx * dx + dy * dy;
}
function boxD2(b, q) {
  const dx = q.x < b.minX ? b.minX - q.x :
    q.x > b.maxX ? q.x - b.maxX : 0n;
  const dy = q.y < b.minY ? b.minY - q.y :
    q.y > b.maxY ? q.y - b.maxY : 0n;
  return dx * dx + dy * dy;
}
function nearest(root, q, stats = {}) {
  checkXY(q);
  stats.visited = 0; stats.pruned = 0;
  let best = null;
  function visit(n) {
    if (!n) return;
    // Equality must remain searchable: a smaller id may still win.
    if (best && boxD2(n, q) > best.d2) { stats.pruned++; return; }
    stats.visited++;
    const d2 = pointD2(n.p, q);
    if (!best || d2 < best.d2 || (d2 === best.d2 && n.p.id < best.id))
      best = { id: n.p.id, d2 };
    let first = n.left, second = n.right;
    if (first && second && boxD2(first, q) > boxD2(second, q))
      [first, second] = [second, first];
    visit(first);
    visit(second); // Recheck its bound against the UPDATED best.
  }
  visit(root);
  return best;
}
function brute(points, q) {
  let answer = null;
  for (const p of points) {
    const a = p.x - q.x, b = p.y - q.y;
    const distance = a ** 2n + b ** 2n;
    if (answer === null || distance < answer.d2 ||
        (distance === answer.d2 && p.id < answer.id))
      answer = { id: p.id, d2: distance };
  }
  return answer;
}
const grid = [], queries = [];
for (let x = -1n; x <= 1n; x++)
  for (let y = -1n; y <= 1n; y++)
    grid.push({ id: String(grid.length), x, y });
for (let x = -2n; x <= 2n; x++)
  for (let y = -2n; y <= 2n; y++) queries.push({ x, y });
let checks = 0;
for (let mask = 0; mask < 2 ** grid.length; mask++) {
  const points = grid.filter((_, i) => (mask & (1 << i)) !== 0);
  for (const ordered of [points, [...points].reverse()]) {
    const tree = build(ordered);
    for (const q of queries) {
      assert.deepEqual(nearest(tree, q), brute(points, q));
      checks++;
    }
  }
}
console.log("subsets: 512, queries: 25, input orders: 2");
console.log("oracle comparisons:", checks);

运行输出:

subsets: 512, queries: 25, input orders: 2
oracle comparisons: 25600

八、固定种子随机测试,把尺度和重复混在一起

随机测试负责补充穷举网格没有覆盖的组合。程序使用固定种子的伪随机发生器,生成五百组、每组最多三十个点的数据;每组做三十次查询。坐标既可能是小整数,也可能放大到十的六十次方附近;每隔三组还主动制造一对重复坐标。建树前打乱顺序,部分查询直接命中已有点,其余查询继续随机生成。

固定种子不是为了让数字看起来科学,而是让失败可以被另一台机器复现。这里的发生器和取模只服务于测试样本生成,不是密码学随机源,也不宣称严格均匀抽样。随机测试仍然无法证明算法正确;它的作用是把不同约束组合起来,检查那些单独测试都通过、合在一起却失败的实现路径。

这也是给 AI 的一条实用约束:不能只返回通过二字,应交付固定种子、样本生成规则、实际比较次数与运行命令。若修改了数值类型、平局规则或包围盒定义,必须重跑这些测试。把测试写进提交内容,比把一次聊天里的信心表态当作长期质量保证更有价值。

独立示例 08:保存为 08.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function checkXY(p) {
  if (!p || typeof p.x !== "bigint" || typeof p.y !== "bigint")
    throw new TypeError("x and y must be BigInt");
}
function copyPoints(input) {
  if (!Array.isArray(input)) throw new TypeError("points must be an array");
  const ids = new Set();
  return Array.from(input, p => {
    checkXY(p);
    if (typeof p.id !== "string" || p.id.length === 0 || ids.has(p.id))
      throw new TypeError("ids must be nonempty unique strings");
    ids.add(p.id);
    return Object.freeze({ id: p.id, x: p.x, y: p.y });
  });
}
function build(input) {
  function rec(a, depth) {
    if (a.length === 0) return null;
    const axis = depth % 2 === 0 ? "x" : "y";
    const other = axis === "x" ? "y" : "x";
    a.sort((p, q) => cmp(p[axis], q[axis]) ||
      cmp(p[other], q[other]) || cmp(p.id, q.id));
    const m = Math.floor(a.length / 2), p = a[m];
    const left = rec(a.slice(0, m), depth + 1);
    const right = rec(a.slice(m + 1), depth + 1);
    let minX = p.x, maxX = p.x, minY = p.y, maxY = p.y;
    for (const c of [left, right]) if (c) {
      if (c.minX < minX) minX = c.minX;
      if (c.maxX > maxX) maxX = c.maxX;
      if (c.minY < minY) minY = c.minY;
      if (c.maxY > maxY) maxY = c.maxY;
    }
    return Object.freeze({ p, left, right, minX, maxX, minY, maxY });
  }
  return rec(copyPoints(input), 0);
}
function pointD2(p, q) {
  const dx = p.x - q.x, dy = p.y - q.y;
  return dx * dx + dy * dy;
}
function boxD2(b, q) {
  const dx = q.x < b.minX ? b.minX - q.x :
    q.x > b.maxX ? q.x - b.maxX : 0n;
  const dy = q.y < b.minY ? b.minY - q.y :
    q.y > b.maxY ? q.y - b.maxY : 0n;
  return dx * dx + dy * dy;
}
function nearest(root, q, stats = {}) {
  checkXY(q);
  stats.visited = 0; stats.pruned = 0;
  let best = null;
  function visit(n) {
    if (!n) return;
    // Equality must remain searchable: a smaller id may still win.
    if (best && boxD2(n, q) > best.d2) { stats.pruned++; return; }
    stats.visited++;
    const d2 = pointD2(n.p, q);
    if (!best || d2 < best.d2 || (d2 === best.d2 && n.p.id < best.id))
      best = { id: n.p.id, d2 };
    let first = n.left, second = n.right;
    if (first && second && boxD2(first, q) > boxD2(second, q))
      [first, second] = [second, first];
    visit(first);
    visit(second); // Recheck its bound against the UPDATED best.
  }
  visit(root);
  return best;
}
function brute(points, q) {
  let answer = null;
  for (const p of points) {
    const a = p.x - q.x, b = p.y - q.y;
    const distance = a ** 2n + b ** 2n;
    if (answer === null || distance < answer.d2 ||
        (distance === answer.d2 && p.id < answer.id))
      answer = { id: p.id, d2: distance };
  }
  return answer;
}
let state = 0x12345678;
function randomInt(n) {
  state ^= state << 13; state ^= state >>> 17; state ^= state << 5;
  return (state >>> 0) % n;
}
function coord() {
  const offset = BigInt(randomInt(21) - 10);
  return randomInt(4) === 0 ? offset * (10n ** 60n) : offset;
}
let checks = 0;
for (let trial = 0; trial < 500; trial++) {
  const points = Array.from({ length: randomInt(31) }, (_, i) => ({
    id: `p${String(i).padStart(2, "0")}`, x: coord(), y: coord()
  }));
  if (points.length > 1 && trial % 3 === 0) {
    points[1].x = points[0].x; points[1].y = points[0].y;
  }
  for (let i = points.length - 1; i > 0; i--) {
    const j = randomInt(i + 1);
    [points[i], points[j]] = [points[j], points[i]];
  }
  const tree = build(points);
  for (let j = 0; j < 30; j++) {
    const q = j === 0 && points.length ? points[0] : { x: coord(), y: coord() };
    assert.deepEqual(nearest(tree, q), brute(points, q));
    checks++;
  }
}
console.log("seed: 0x12345678, datasets: 500");
console.log("random oracle comparisons:", checks);

运行输出:

seed: 0x12345678, datasets: 500
random oracle comparisons: 15000

九、用一个确定反例拆穿查询恒为对数的说法

最后故意制造一千零二十三个坐标完全相同、ID 各不相同的点,查询也落在这个位置。树依然按中位数建立,树高仍然是对数量级,但所有子树包围盒下界都是零,而最优距离也是零。因为 ID 平局必须继续核对,当前实现无法用严格大于条件排除任何子树,最终会访问全部节点。

所以,对这份精确实现,最近邻查询的最坏节点访问次数是 O(n),而不是 O(log n)。数据分布较友好时,优先访问近盒子常常有助于减少访问;实际效果应该测量,不能从平衡树高直接推导。可以增加每个子树的最小 ID 等元数据来加强相等下界时的判定,但那会形成新的不变量与剪枝证明,本教程刻意保留更容易核验的基本版本。

建树也不能随口写成 O(n log n)。本实现每层重新排序:在每次长度为 m 的排序使用 O(m log m) 比较的假设下,整体是 O(n log² n) 比较量级,复制和切片的累计元素量是 O(n log n),最终树存储 O(n) 个节点。ECMAScript 没有承诺所有引擎的排序复杂度;V8 对排序实现的说明可帮助理解具体引擎的选择。把比较、ID 长度和大整数位运算成本都计入后,实际时间还需要更细的模型。

独立示例 09:保存为 09.cjs 后执行。

"use strict";
const assert = require("node:assert/strict");
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function checkXY(p) {
  if (!p || typeof p.x !== "bigint" || typeof p.y !== "bigint")
    throw new TypeError("x and y must be BigInt");
}
function copyPoints(input) {
  if (!Array.isArray(input)) throw new TypeError("points must be an array");
  const ids = new Set();
  return Array.from(input, p => {
    checkXY(p);
    if (typeof p.id !== "string" || p.id.length === 0 || ids.has(p.id))
      throw new TypeError("ids must be nonempty unique strings");
    ids.add(p.id);
    return Object.freeze({ id: p.id, x: p.x, y: p.y });
  });
}
function build(input) {
  function rec(a, depth) {
    if (a.length === 0) return null;
    const axis = depth % 2 === 0 ? "x" : "y";
    const other = axis === "x" ? "y" : "x";
    a.sort((p, q) => cmp(p[axis], q[axis]) ||
      cmp(p[other], q[other]) || cmp(p.id, q.id));
    const m = Math.floor(a.length / 2), p = a[m];
    const left = rec(a.slice(0, m), depth + 1);
    const right = rec(a.slice(m + 1), depth + 1);
    let minX = p.x, maxX = p.x, minY = p.y, maxY = p.y;
    for (const c of [left, right]) if (c) {
      if (c.minX < minX) minX = c.minX;
      if (c.maxX > maxX) maxX = c.maxX;
      if (c.minY < minY) minY = c.minY;
      if (c.maxY > maxY) maxY = c.maxY;
    }
    return Object.freeze({ p, left, right, minX, maxX, minY, maxY });
  }
  return rec(copyPoints(input), 0);
}
function pointD2(p, q) {
  const dx = p.x - q.x, dy = p.y - q.y;
  return dx * dx + dy * dy;
}
function boxD2(b, q) {
  const dx = q.x < b.minX ? b.minX - q.x :
    q.x > b.maxX ? q.x - b.maxX : 0n;
  const dy = q.y < b.minY ? b.minY - q.y :
    q.y > b.maxY ? q.y - b.maxY : 0n;
  return dx * dx + dy * dy;
}
function nearest(root, q, stats = {}) {
  checkXY(q);
  stats.visited = 0; stats.pruned = 0;
  let best = null;
  function visit(n) {
    if (!n) return;
    // Equality must remain searchable: a smaller id may still win.
    if (best && boxD2(n, q) > best.d2) { stats.pruned++; return; }
    stats.visited++;
    const d2 = pointD2(n.p, q);
    if (!best || d2 < best.d2 || (d2 === best.d2 && n.p.id < best.id))
      best = { id: n.p.id, d2 };
    let first = n.left, second = n.right;
    if (first && second && boxD2(first, q) > boxD2(second, q))
      [first, second] = [second, first];
    visit(first);
    visit(second); // Recheck its bound against the UPDATED best.
  }
  visit(root);
  return best;
}
const n = 1023;
const points = Array.from({ length: n }, (_, i) => ({
  id: String(i).padStart(4, "0"), x: 7n, y: -3n
}));
const stats = {}, hit = nearest(build(points), { x: 7n, y: -3n }, stats);
assert.deepEqual(hit, { id: "0000", d2: 0n });
assert.equal(stats.visited, n);
assert.equal(stats.pruned, 0);
console.log("winner:", hit.id, "squared distance:", hit.d2.toString());
console.log("visited:", stats.visited, "of", n, "pruned:", stats.pruned);
console.log("balanced tree still has a linear worst case");

运行输出:

winner: 0000 squared distance: 0
visited: 1023 of 1023 pruned: 0
balanced tree still has a linear worst case

把审查结论变成一张真正可执行的清单

到这里,AI 生成的程序有没有通过审查,不再取决于解释是否流畅,而取决于几个可以逐项回答的问题:输入是否在进入算法之前就保持精确;所有候选是否遵守同一个平局规则;包围盒是否包含真实子树;下界相等时是否保留潜在赢家;第二个分支是否使用更新后的候选;空树和非法输入是否按照约定处理;复杂度是否诚实标注最坏情况。

本文选择静态二维整数,是为了让这些判断能够闭合。若接下来要加入动态更新,必须同步维护包围盒并考虑重建;若要支持浮点坐标,就需要重新讨论非有限值、舍入和相等语义;若要返回前 k 个邻居,就需要候选集合而非单个 best;若维度增加,包围盒剪枝效果也不能沿用二维经验。不要把这些扩展当成修改一行参数就能继承的正确性。

最终值得保留的不是某一段递归代码,而是一套合作方式:先约定结果,再建立简单裁判;把复杂算法拆成可单独验证的不变量;让反例逼出边界;用穷举和可复现随机测试增加证据;最后把所有性能承诺限定在真实的成本模型里。AI 可以快速提出实现,但决定它能否进入项目的,应当是这些可检查的证据。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。