用 Node.js 验证鸿蒙数独规则:把行、列、宫的冲突单独测出来

举报
yd_259622877 发表于 2026/11/12 14:13:31 2026/11/12
【摘要】 把鸿蒙数独项目的纯逻辑移到 Node.js 运行,用隔离用例分别验证同行、同列、同宫的冲突下标,再检查清空重复数字、通关条件和题库预填一致性。文中提供固定源码版本、可直接运行的脚本和实际验证结果。

为什么要比对冲突的下标

鸿蒙数独项目把棋盘存成长度为 81 的一维数组。行列从 0 开始计数,下标等于 行号 × 9 + 列号,数字 0 代表空格。规则函数 computeConflicts(grid) 检查 9 行、9 列和 9 个 3×3 宫,返回长度为 81 的布尔数组。每个有重复的数字都应对应一个 true,这样棋盘才能把同组内涉及冲突的格子都标出来。

我的第一组同行用例把数字 5 放在下标 0 和 1,第一组同列用例放在 0 和 9。两对格子都在左上宫。即使同行和同列检查都被漏掉,只靠宫检查也能得到预期的冲突下标。把样例的空格保留,只移动第二个 5,就能分别触发三条规则。

样例 填入 5 的下标 期望冲突下标
同行且分属不同宫 [0, 3] [0, 3]
同列且分属不同宫 [0, 27] [0, 27]
同宫且分属不同行、列 [0, 10] [0, 10]
相同数字分散到不同的行、列、宫 [0, 40, 80] []
下标 0 同时参与同行、同列冲突 [0, 3, 27] [0, 3, 27]

直接比对下标可以同时发现漏标和误标。最后一组再把下标 3 清零,预期只有 0 和 27 保留冲突。此时仍与 27 重复的下标 0 应继续高亮。

在 Node.js 中复现

使用已下载的公开仓库,切换到本次验证的版本。在仓库根目录把下方脚本保存为 verify-sudoku.mjs。我使用 Node.js v24.18.0,在临时目录里把三个纯逻辑文件的后缀改为 .ts,并调整相对导入和类型导入,保留原来的算法和题库实现。脚本运行后清理临时副本。

git checkout --detach 0edfc16bf8bb0a430ad71ed334bd8d97a72fc329
node --experimental-transform-types verify-sudoku.mjs
import assert from 'node:assert/strict';
import { mkdtemp, readFile, rm, rmdir, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';

const source = join(
  process.cwd(), 'harmony_app', 'entry', 'src', 'main', 'ets', 'sudoku'
);
const modules = ['SudokuTypes', 'SudokuLogic', 'SudokuPuzzleLibrary'];
const work = await mkdtemp(join(tmpdir(), 'sudoku-check-'));

try {
  await writeFile(join(work, 'package.json'), '{"type":"module"}');
  for (const name of modules) {
    const original = await readFile(join(source, `${name}.ets`), 'utf8');
    const adapted = original
      .replace("from './SudokuTypes'", "from './SudokuTypes.ts'")
      .replace('{ Difficulty, PuzzleData }', '{ Difficulty, type PuzzleData }');
    await writeFile(join(work, `${name}.ts`), adapted);
  }

  const { computeConflicts, countEmpty, isSolved, parseGrid } =
    await import(pathToFileURL(join(work, 'SudokuLogic.ts')).href);
  const { SudokuPuzzleLibrary } =
    await import(pathToFileURL(join(work, 'SudokuPuzzleLibrary.ts')).href);

  function gridWithFives(indices) {
    const grid = Array(81).fill(0);
    for (const index of indices) {
      grid[index] = 5;
    }
    return grid;
  }

  function conflictIndices(grid) {
    const mask = computeConflicts(grid);
    assert.equal(mask.length, 81);
    return mask.flatMap((conflict, index) => conflict ? [index] : []);
  }

  for (const [label, input, expected] of [
    ['同行', [0, 3], [0, 3]],
    ['同列', [0, 27], [0, 27]],
    ['同宫', [0, 10], [0, 10]],
    ['分散', [0, 40, 80], []],
    ['交叠', [0, 3, 27], [0, 3, 27]],
  ]) {
    assert.deepEqual(conflictIndices(gridWithFives(input)), expected, label);
  }
  const edited = gridWithFives([0, 3, 27]);
  edited[3] = 0;
  assert.deepEqual(conflictIndices(edited), [0, 27], '清除同行冲突');

  const solvedText = [
    '534678912', '672195348', '198342567',
    '859761423', '426853791', '713924856',
    '961537284', '287419635', '345286179',
  ].join('');
  for (const [label, input, expected] of [
    ['合法终盘', solvedText, true],
    ['仍有空格', '0' + solvedText.slice(1), false],
    ['满盘但重复', solvedText[1] + solvedText.slice(1), false],
  ]) {
    const grid = parseGrid(input);
    assert.equal(isSolved(grid, computeConflicts(grid)), expected, label);
  }

  const puzzles = SudokuPuzzleLibrary.all();
  assert.equal(puzzles.length, 54);
  assert.equal(new Set(puzzles.map(puzzle => puzzle.id)).size, 54);
  const expectedHoles = [38, 47, 54];
  for (const [difficulty, holes] of expectedHoles.entries()) {
    const group = puzzles.filter(puzzle => puzzle.difficulty === difficulty);
    assert.equal(group.length, 18, `难度 ${difficulty} 的题量`);
    for (const { id, puzzle, solution } of group) {
      assert.match(puzzle, /^[0-9]{81}$/, `题面 ${id}`);
      assert.match(solution, /^[1-9]{81}$/, `答案 ${id}`);
      const givens = parseGrid(puzzle);
      const answer = parseGrid(solution);
      assert.equal(countEmpty(givens), holes, `挖空数 ${id}`);
      assert.equal(isSolved(answer, computeConflicts(answer)), true, `终盘 ${id}`);
      assert.ok(givens.every((value, i) => value === 0 || value === answer[i]),
        `预填格与答案一致 ${id}`);
    }
  }
  console.log('通过:6 个冲突场景,3 个通关场景,54 道题的题库检查。');
} finally {
  for (const file of ['package.json', ...modules.map(name => name + '.ts')]) {
    await rm(join(work, file), { force: true });
  }
  await rmdir(work);
}

本次验证覆盖了什么

脚本在 Node.js v24.18.0 运行通过。6 个冲突场景返回了预期的下标,3 个通关场景分别返回 true、false 和 false。题库的 54 道题都有不同的 ID,简单、中等、困难各 18 道,对应挖空 38、47 和 54 格。逐题检查确认答案符合行、列、宫规则,且题面的每个预填数字都与所附答案一致。

通关判断要使用从当前棋盘计算的冲突数组,填入或清除数字后都要重新计算。题库检查确认每道题至少有一个有效解。要证明唯一解,还要让求解器枚举到第二个解就停止,并逐题断言解的数量为 1。原项目的 parseGrid 按 81 个数字字符的约定读取输入,因此脚本也单独检查了题库字符串的格式。

这次实测覆盖 Node.js 中运行的数独纯逻辑。ArkTS 编译、HAP 安装、棋盘上实际的高亮和通关反馈、重启后进度恢复,都要在 HarmonyOS 构建和设备环境中验证。

鸿蒙开发实践中心的公开数独源码

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。