HarmonyOS数独候选台连载06:候选增量刷新与缓存失效【共创稿事节】

每填一个数字都重新查询全部空格,虽然能够得到正确候选,却把与本次变化无关的位置也重复计算。若只刷新目标格,又会让同行、同列或同宫的提示继续使用旧集合。数独候选台在合法题面提交之后增加候选缓存,通过比较前后棋盘收集受影响区域,再用完整重算结果核对增量路径。

候选增量刷新与缓存失效

缓存属于题面派生数据

棋盘数字仍保存在PuzzleHistory中,候选缓存保存一份对应的棋盘副本,以及八十一项候选记录。空格保存CandidateInfo,已有数字的位置保存空项。缓存记录的是当前题面能够推导出的集合,不能作为修改棋盘数字的另一个入口。

前文候选类型不仅保存可填数字,也保存行、列、宫三个已用集合。本篇会一并刷新这些解释字段。即使某格最终候选没有变化,只要来源集合发生变化,解释也需要更新,不能仅比较values是否相等就决定继续保留旧对象。

SudokuDesk沿用题面、候选、编辑事务、单步提示、历史与搜索六个完整文件。新增缓存服务和页面同样放在entry/src/main/ets对应目录。搜索在自己的工作副本上继续调用纯候选服务,页面缓存只服务已经接受的用户题面,不随搜索试填而反复变化。

// model/Puzzle.ets
export function initialPuzzle(): number[] {
  const rows: string[] = ['530070000','600195000','098000060',
    '800060003','400803001','700020006','060000280','000419005','000080079'];
  const board: number[] = [];
  for (const row of rows) for (let col: number = 0; col<9; col++) board.push(Number(row[col]));
  return board;
}
export function requireBoard(board: number[]): void {
  if (board.length!==81) throw new Error('题面需为81格');
  for (const value of board) if (!Number.isInteger(value) || value<0 || value>9)
    throw new Error('题面格值需为0至9');
}
export function parseCell(rowText: string,colText: string): number {
  const row: string = rowText.trim(); const col: string = colText.trim();
  if (!/^[1-9]$/.test(row) || !/^[1-9]$/.test(col)) throw new Error('行列需为1至9');
  return (Number(row)-1)*9+Number(col)-1;
}
// service/Candidates.ets
import { requireBoard } from '../model/Puzzle';
export interface CandidateInfo { rowUsed: number[]; colUsed: number[]; boxUsed: number[]; values: number[]; }
function uniqueDigits(values: number[]): number[] {
  const result: number[] = [];
  for (let value: number = 1; value<=9; value++) if (values.indexOf(value)>=0) result.push(value);
  return result;
}
export function queryCandidates(board: number[],index: number): CandidateInfo {
  requireBoard(board);
  if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
  if (board[index]!==0) throw new Error('目标格已有数字');
  const row: number = Math.floor(index/9); const col: number = index%9;
  const rowValues: number[] = []; const colValues: number[] = []; const boxValues: number[] = [];
  for (let offset: number = 0; offset<9; offset++) {
    rowValues.push(board[row*9+offset]); colValues.push(board[offset*9+col]);
  }
  const top: number = Math.floor(row/3)*3; const left: number = Math.floor(col/3)*3;
  for (let dr: number = 0; dr<3; dr++) for (let dc: number = 0; dc<3; dc++)
    boxValues.push(board[(top+dr)*9+left+dc]);
  const rowUsed: number[] = uniqueDigits(rowValues);
  const colUsed: number[] = uniqueDigits(colValues);
  const boxUsed: number[] = uniqueDigits(boxValues);
  const used: boolean[] = [false,false,false,false,false,false,false,false,false,false];
  for (const value of rowUsed.concat(colUsed,boxUsed)) used[value]=true;
  const result: number[] = [];
  for (let value: number = 1; value<=9; value++) {
    if (!used[value]) result.push(value);
  }
  return {rowUsed,colUsed,boxUsed,values:result};
}
export function digitsText(values: number[]): string { return values.length===0 ? '无' : values.join('、'); }
// service/PuzzleEdit.ets
import { initialPuzzle, requireBoard } from '../model/Puzzle';
export interface PuzzleState { board: number[]; givens: boolean[]; }
export type UnitKind = 'row' | 'col' | 'box';
export interface Conflict { kind: UnitKind; unit: number; digit: number; indices: number[]; }
export function createPuzzleState(): PuzzleState {
  const board: number[] = initialPuzzle();
  return {board,givens:board.map((value: number) => value!==0)};
}
export function requirePuzzleState(state: PuzzleState): void {
  requireBoard(state.board);
  if (state.givens.length!==81) throw new Error('固定格标记长度错误');
  const seed: number[] = initialPuzzle();
  for (let i: number = 0; i<81; i++) {
    if (state.givens[i] !== (seed[i]!==0) || (seed[i]!==0 && state.board[i]!==seed[i]))
      throw new Error('固定题面不一致');
  }
}
export function unitIndices(kind: UnitKind,unit: number): number[] {
  if (!Number.isInteger(unit) || unit<0 || unit>=9) throw new Error('区域位置错误');
  if (kind!=='row' && kind!=='col' && kind!=='box') throw new Error('区域类型错误');
  const result: number[] = [];
  for (let offset: number = 0; offset<9; offset++) {
    if (kind==='row') result.push(unit*9+offset);
    else if (kind==='col') result.push(offset*9+unit);
    else result.push((Math.floor(unit/3)*3+Math.floor(offset/3))*9+(unit%3)*3+offset%3);
  }
  return result;
}
export function findConflicts(board: number[]): Conflict[] {
  requireBoard(board);
  const result: Conflict[] = [];
  const kinds: UnitKind[] = ['row','col','box'];
  for (const kind of kinds) for (let unit: number = 0; unit<9; unit++) {
    const points: number[] = unitIndices(kind,unit);
    for (let digit: number = 1; digit<=9; digit++) {
      const matches: number[] = points.filter((index: number) => board[index]===digit);
      if (matches.length>1) result.push({kind,unit,digit,indices:matches});
    }
  }
  return result;
}
export function conflictText(conflict: Conflict): string {
  const name: string = conflict.kind==='row' ? '行' : conflict.kind==='col' ? '列' : '宫';
  return `第${conflict.unit+1}${name}数字${conflict.digit}重复`;
}
export function parseDigit(text: string): number {
  const value: string = text.trim();
  if (!/^[0-9]$/.test(value)) throw new Error('填入值需为0至9,0表示清空');
  return Number(value);
}
export function commitEdit(state: PuzzleState,index: number,value: number): PuzzleState {
  requirePuzzleState(state);
  if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
  if (!Number.isInteger(value) || value<0 || value>9) throw new Error('填入值超出范围');
  if (state.givens[index]) throw new Error('固定题面格不可修改');
  if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
  const next: number[] = state.board.slice(); next[index]=value;
  const conflicts: Conflict[] = findConflicts(next);
  if (conflicts.length>0) throw new Error(conflictText(conflicts[0]));
  return {board:next,givens:state.givens.slice()};
}
// service/SingleHint.ets
import { CandidateInfo, queryCandidates } from './Candidates';
import { PuzzleState, requirePuzzleState, findConflicts, commitEdit } from './PuzzleEdit';
export interface SingleHint { index: number; value: number; boardKey: string; info: CandidateInfo; }
export function findSingleHints(state: PuzzleState): SingleHint[] {
  requirePuzzleState(state);
  if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
  const result: SingleHint[] = [];
  const boardKey: string = state.board.join('');
  for (let index: number = 0; index<81; index++) {
    if (state.board[index]!==0) continue;
    const info: CandidateInfo = queryCandidates(state.board,index);
    if (info.values.length===1) {
      result.push({index,value:info.values[0],boardKey,info});
    }
  }
  return result;
}
export function applySingleHint(state: PuzzleState,hint: SingleHint): PuzzleState {
  requirePuzzleState(state);
  if (state.board.join('')!==hint.boardKey) throw new Error('题面已变化,请刷新提示');
  const current: CandidateInfo = queryCandidates(state.board,hint.index);
  if (current.values.length!==1 || current.values[0]!==hint.value)
    throw new Error('当前格不满足单格唯一候选');
  return commitEdit(state,hint.index,hint.value);
}
export function hintText(hint: SingleHint): string {
  return `${Math.floor(hint.index/9)+1}行${hint.index%9+1}列填${hint.value}`;
}
// service/History.ets
import { PuzzleState, createPuzzleState, commitEdit } from './PuzzleEdit';
export interface EditStep { index: number; before: number; after: number; group: string; }
export interface PuzzleHistory { state: PuzzleState; steps: EditStep[]; cursor: number; }
export function createHistory(): PuzzleHistory { return {state:createPuzzleState(),steps:[],cursor:0}; }
function copyStep(step: EditStep): EditStep {
  return {index:step.index,before:step.before,after:step.after,group:step.group};
}
export function recordEdit(history: PuzzleHistory,index: number,value: number,group: string): PuzzleHistory {
  const next: PuzzleState = commitEdit(history.state,index,value);
  const before: number = history.state.board[index];
  if (before===value) return history;
  const steps: EditStep[] = history.steps.slice(0,history.cursor).map(copyStep);
  const last: EditStep | undefined = steps.length>0 ? steps[steps.length-1] : undefined;
  const atEnd: boolean = history.cursor===history.steps.length;
  if (atEnd && group.length>0 && last!==undefined && last.index===index && last.group===group && last.after===before) {
    if (last.before===value) steps.pop();
    else steps[steps.length-1]={index,before:last.before,after:value,group};
  } else steps.push({index,before,after:value,group});
  return {state:next,steps,cursor:steps.length};
}
export function undo(history: PuzzleHistory): PuzzleHistory {
  if (history.cursor===0) throw new Error('没有可撤销步骤');
  const step: EditStep = history.steps[history.cursor-1];
  if (history.state.board[step.index]!==step.after) throw new Error('历史与题面不一致');
  return {state:commitEdit(history.state,step.index,step.before),steps:history.steps.map(copyStep),cursor:history.cursor-1};
}
export function redo(history: PuzzleHistory): PuzzleHistory {
  if (history.cursor===history.steps.length) throw new Error('没有可重做步骤');
  const step: EditStep = history.steps[history.cursor];
  if (history.state.board[step.index]!==step.before) throw new Error('历史与题面不一致');
  return {state:commitEdit(history.state,step.index,step.after),steps:history.steps.map(copyStep),cursor:history.cursor+1};
}
// service/Search.ets
import { requireBoard } from '../model/Puzzle';
import { queryCandidates } from './Candidates';
import { findConflicts } from './PuzzleEdit';
export interface SearchReport { status: string; solutions: number; nodes: number; cutoff: boolean; first: number[]; boardKey: string; }
export function idleReport(): SearchReport {
  return {status:'待分析',solutions:0,nodes:0,cutoff:false,first:[],boardKey:''};
}
export function parseBudget(text: string): number {
  const value: string = text.trim();
  if (!/^[1-9][0-9]{0,4}$/.test(value) || Number(value)>10000) throw new Error('节点预算需为1至10000');
  return Number(value);
}
export function analyzePuzzle(source: number[],budget: number): SearchReport {
  requireBoard(source);
  if (findConflicts(source).length>0) throw new Error('当前题面存在冲突');
  if (!Number.isInteger(budget) || budget<1 || budget>10000) throw new Error('节点预算超出范围');
  const board: number[] = source.slice();
  const report: SearchReport = idleReport(); report.boardKey=source.join('');
  function visit(): void {
    if (report.solutions>=2 || report.cutoff) return;
    if (report.nodes>=budget) { report.cutoff=true; return; }
    report.nodes++;
    let target: number = -1; let values: number[] = [];
    for (let i: number = 0; i<81; i++) {
      if (board[i]!==0) continue;
      const options: number[] = queryCandidates(board,i).values;
      if (options.length===0) return;
      if (target<0 || options.length<values.length) { target=i; values=options; }
    }
    if (target<0) {
      report.solutions++;
      if (report.solutions===1) report.first=board.slice();
      return;
    }
    for (const value of values) {
      board[target]=value; visit(); board[target]=0;
      if (report.solutions>=2 || report.cutoff) return;
    }
  }
  visit();
  report.status=report.solutions>=2 ? '至少两解' : report.cutoff ? '尚未判定' : report.solutions===1 ? '唯一解' : '无解';
  return report;
}

变化格决定刷新区域

更新入口比较旧缓存中的棋盘副本与新棋盘,逐格找出值不同的位置。每个变化格所在行、列、宫的全部位置进入布尔标记数组,相同位置只标记一次。这样既能处理单次填写,也能处理撤销、重做或后续一次恢复多格的场景。

一个格对应的行、列、宫并集包含它自身和二十个同伴,共二十一格。不能把三个九格区域简单相加成二十七,因为交叉位置重复出现。使用与冲突服务相同的unitIndices生成区域索引,可避免缓存层另写一套宫坐标规则。

影响范围包括已有数字和空格,但真正需要候选查询的是影响范围内的新空格。新题面中已填的位置直接置为空项,其他未受影响空格复制原候选记录。首次创建则扫描所有空格,建立与当前题面完全一致的基线。

// service/CandidateCache.ets
import { requireBoard } from '../model/Puzzle';
import { CandidateInfo, queryCandidates } from './Candidates';
import { PuzzleState, requirePuzzleState, findConflicts, unitIndices } from './PuzzleEdit';
import { SingleHint } from './SingleHint';
export interface CandidateCache { board: number[]; entries: (CandidateInfo | null)[]; }
export interface CacheUpdate { cache: CandidateCache; changed: number; affected: number; recomputed: number; }
function copyInfo(info: CandidateInfo): CandidateInfo {
  return {rowUsed:info.rowUsed.slice(),colUsed:info.colUsed.slice(),boxUsed:info.boxUsed.slice(),values:info.values.slice()};
}
export function createCache(board: number[]): CandidateCache {
  requireBoard(board);
  const entries: (CandidateInfo | null)[] = [];
  for (let i: number = 0; i<81; i++) entries.push(board[i]===0 ? queryCandidates(board,i) : null);
  return {board:board.slice(),entries};
}
export function updateCache(previous: CandidateCache,board: number[]): CacheUpdate {
  requireBoard(previous.board); requireBoard(board);
  if (previous.entries.length!==81) throw new Error('候选缓存长度错误');
  const flags: boolean[] = [];
  for (let i: number = 0; i<81; i++) flags.push(false);
  let changed: number = 0;
  for (let i: number = 0; i<81; i++) {
    if (previous.board[i]===board[i]) continue;
    changed++;
    const row: number = Math.floor(i/9); const col: number = i%9;
    const points: number[] = unitIndices('row',row).concat(unitIndices('col',col),unitIndices('box',Math.floor(row/3)*3+Math.floor(col/3)));
    for (const point of points) flags[point]=true;
  }
  const entries: (CandidateInfo | null)[] = [];
  let affected: number = 0; let recomputed: number = 0;
  for (let i: number = 0; i<81; i++) {
    if (flags[i]) affected++;
    if (board[i]!==0) { entries.push(null); continue; }
    const old: CandidateInfo | null = previous.entries[i];
    if (flags[i] || old===null) { entries.push(queryCandidates(board,i)); recomputed++; }
    else entries.push(copyInfo(old));
  }
  return {cache:{board:board.slice(),entries},changed,affected,recomputed};
}
export function readCandidate(cache: CandidateCache,index: number): CandidateInfo {
  if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('缓存位置错误');
  const entry: CandidateInfo | null = cache.entries[index];
  if (entry===null) throw new Error('目标格已有数字');
  return copyInfo(entry);
}
export function hintsFromCache(cache: CandidateCache,state: PuzzleState): SingleHint[] {
  requirePuzzleState(state);
  if (cache.board.join('')!==state.board.join('')) throw new Error('缓存题面不一致');
  if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
  const hints: SingleHint[] = []; const boardKey: string = state.board.join('');
  for (let index: number = 0; index<81; index++) {
    if (state.board[index]!==0) continue;
    const info: CandidateInfo = readCandidate(cache,index);
    if (info.values.length===1) hints.push({index,value:info.values[0],boardKey,info});
  }
  return hints;
}

缓存记录也需要隔离

更新函数建立新的棋盘副本、记录数组和候选子数组。未受影响的记录虽然数值可以复用,仍通过copyInfo复制四个数组,避免调用方修改返回结果后把旧缓存也改掉。readCandidate同样返回副本,界面获得解释数据以后不能反向污染缓存内部。

缓存对象由createCache和updateCache维护,页面以整体替换方式发布,不对entries逐项写入。读取某个已填格会被拒绝,页面应显示目标格已填,而不是继续保留该格之前为空时的候选。清空用户格以后,该位置重新参与候选计算。

缓存结构是内部派生对象,题面输入仍必须通过原编辑事务。缓存更新只负责计算,不承担固定格权限与合法写入裁决。对完整状态生成提示时,再核对缓存棋盘与状态棋盘一致,并检查全题冲突,防止解释来自另一份题面。

提示从缓存生成,应用仍重新检查

hintsFromCache逐个读取空格记录,只为候选数量为一的位置生成提示,顺序与上一章之前的扫描方式一致。每条提示中的行列宫集合来自当前缓存,题面内容标识也来自当前数字数组。这样提示刷新不再对每个空格重复调用纯候选查询。

用户应用提示时,原applySingleHint仍然重新查询当前目标候选,再通过commitEdit裁决。缓存用于减少重复派生,不能取代写入前的合法性检查。手动填写、提示应用和历史恢复完成后,再将接受的新题面交给缓存更新入口。

// pages/Index.ets
import { initialPuzzle, parseCell } from '../model/Puzzle';
import { CandidateInfo, queryCandidates, digitsText } from '../service/Candidates';
import { PuzzleState, createPuzzleState, commitEdit, findConflicts, parseDigit } from '../service/PuzzleEdit';
import { SingleHint, findSingleHints, applySingleHint, hintText } from '../service/SingleHint';
import { PuzzleHistory, createHistory, recordEdit, undo, redo } from '../service/History';
import { SearchReport, idleReport, analyzePuzzle, parseBudget } from '../service/Search';
import { CandidateCache, CacheUpdate, createCache, updateCache, readCandidate, hintsFromCache } from '../service/CandidateCache';
@Entry
@Component
struct Index {
  @State cache: CandidateCache = createCache(initialPuzzle());
  @State changedCount: number = 0;
  @State affectedCount: number = 0;
  @State recomputedCount: number = 51;
  @State report: SearchReport = idleReport();
  @State budgetText: string = '10000';
  @State history: PuzzleHistory = createHistory();
  @State hints: SingleHint[] = hintsFromCache(createCache(initialPuzzle()),createPuzzleState());
  @State hintIndex: number = 40;
  @State digitText: string = '1';
  @State candidateText: string = '候选:1、2、4';
  @State rowText: string = '1';
  @State colText: string = '3';
  @State selected: number = 2;
  @State info: CandidateInfo = queryCandidates(initialPuzzle(),2);
  @State status: string = '已更新';
  @State areaWidth: number = 360;
  private publishCache(update: CacheUpdate): void {
    this.cache=update.cache; this.changedCount=update.changed;
    this.affectedCount=update.affected; this.recomputedCount=update.recomputed;
  }
  private analyze(): void {
    try {
      const report: SearchReport = analyzePuzzle(this.history.state.board,parseBudget(this.budgetText));
      this.report=report; this.status='分析完成';
    } catch (error) { this.status=error instanceof Error ? error.message : '分析失败'; }
  }
  private query(): void {
    try {
      const index: number = parseCell(this.rowText,this.colText);
      const next: CandidateInfo = readCandidate(this.cache,index);
      this.selected=index; this.info=next; this.candidateText=`候选:${digitsText(next.values)}`; this.status='已查询';
    } catch (error) { this.status=error instanceof Error ? error.message : '查询失败'; }
  }
  private submit(): void {
    try {
      const index: number = parseCell(this.rowText,this.colText);
      const value: number = parseDigit(this.digitText);
      const history: PuzzleHistory = recordEdit(this.history,index,value,`manual:${index}`);
      const next: PuzzleState = history.state;
      const update: CacheUpdate = updateCache(this.cache,next.board);
      const hints: SingleHint[] = hintsFromCache(update.cache,next);
      this.publishCache(update);
      this.history=history; this.refreshHints(hints); this.selected=index;
      if (value===0) {
        this.info=readCandidate(update.cache,index);
        this.candidateText=`候选:${digitsText(this.info.values)}`;
      } else this.candidateText='目标格已填';
      this.status=`已写入${Math.floor(index/9)+1}行${index%9+1}列`;
    } catch (error) { this.status=error instanceof Error ? error.message : '提交失败'; }
  }
  private refreshHints(hints: SingleHint[]): void {
    const retained: boolean = hints.some((hint: SingleHint) => hint.index===this.hintIndex);
    this.hints=hints;
    if (!retained) this.hintIndex=hints.length>0 ? hints[0].index : -1;
  }
  private applyHint(hint: SingleHint): void {
    try {
      const next: PuzzleState = applySingleHint(this.history.state,hint);
      const history: PuzzleHistory = recordEdit(this.history,hint.index,hint.value,'hint');
      const update: CacheUpdate = updateCache(this.cache,next.board);
      const hints: SingleHint[] = hintsFromCache(update.cache,next);
      this.publishCache(update);
      this.history=history; this.refreshHints(hints); this.selected=hint.index;
      this.candidateText='目标格已填'; this.status=`已应用${hintText(hint)}`;
    } catch (error) { this.status=error instanceof Error ? error.message : '提示应用失败'; }
  }
  private travel(back: boolean): void {
    try {
      const next: PuzzleHistory = back ? undo(this.history) : redo(this.history);
      const update: CacheUpdate = updateCache(this.cache,next.state.board);
      const hints: SingleHint[] = hintsFromCache(update.cache,next.state);
      this.publishCache(update);
      const index: number = back ? this.history.steps[this.history.cursor-1].index : this.history.steps[this.history.cursor].index;
      this.history=next; this.refreshHints(hints); this.selected=index;
      if (next.state.board[index]===0) {
        this.info=readCandidate(update.cache,index); this.candidateText=`候选:${digitsText(this.info.values)}`;
      } else this.candidateText='目标格已填';
      this.status=back ? '已撤销' : '已重做';
    } catch (error) { this.status=error instanceof Error ? error.message : '历史操作失败'; }
  }
  private reset(): void {
    this.history=createHistory(); this.cache=createCache(this.history.state.board); this.changedCount=0; this.affectedCount=81; this.recomputedCount=51; this.refreshHints(hintsFromCache(this.cache,this.history.state)); this.selected=2;
    this.rowText='1'; this.colText='3'; this.digitText='1';
    this.info=queryCandidates(this.history.state.board,2); this.candidateText='候选:1、2、4'; this.status='已恢复题面';
  }
  @Builder
  cachePanel(width: number) {
    Column({space:12}) {
      Text(`当前:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
      Text(`当前格值:${this.history.state.board[this.selected]}`)
      Text(`变化格数:${this.changedCount}`)
      Text(`影响格数:${this.affectedCount}`)
      Text(`重算空格:${this.recomputedCount}`)
      Text(`缓存空格:${this.cache.entries.filter((item: CandidateInfo | null) => item!==null).length}`)
      Text(this.candidateText)
      Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
    }.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
  }
  @Builder
  searchPanel(width: number) {
    Column({space:12}) {
      if (this.report.boardKey===this.history.state.board.join('')) {
        Text(`分析结论:${this.report.status}`).fontSize(26)
        Text(`已找到解数:${this.report.solutions}`)
        Text(`搜索节点:${this.report.nodes}`)
        Text(`预算截断:${this.report.cutoff ? '是' : '否'}`)
      } else { Text('分析结论:待分析').fontSize(26) }
      Text(`当前已填:${this.history.state.board.filter((v: number) => v!==0).length}`)
      Text(`当前空格:${this.history.state.board.filter((v: number) => v===0).length}`)
      Text(`已应用步骤:${this.history.cursor}`)
      Text('搜索参数').fontSize(22)
      TextInput({text:this.budgetText,placeholder:'节点预算1至10000'})
        .onChange((v: string) => { this.budgetText=v; })
      Button('分析当前题面').backgroundColor('#445F97').onClick(() => { this.analyze(); })
      Text(this.status)
    }.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
  }
  @Builder
  historyPanel(width: number) {
    Column({space:12}) {
      Text(`当前:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
      Text(`当前格值:${this.history.state.board[this.selected]}`)
      Text(`已应用步骤:${this.history.cursor}`)
      Text(`可撤销:${this.history.cursor} · 可重做:${this.history.steps.length-this.history.cursor}`)
      if (this.history.cursor>0) {
        Text(`最近步骤:${this.history.steps[this.history.cursor-1].before}→${this.history.steps[this.history.cursor-1].after}`)
      }
      Button('撤销').enabled(this.history.cursor>0).onClick(() => { this.travel(true); })
      Button('重做').enabled(this.history.cursor<this.history.steps.length).onClick(() => { this.travel(false); })
      Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
      Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
    }.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
  }
  @Builder
  hintDetail(hint: SingleHint) {
    Column({space:12}) {
      Text(`提示:${hintText(hint)}`).fontSize(22)
      Text(`行已用:${digitsText(hint.info.rowUsed)}`)
      Text(`列已用:${digitsText(hint.info.colUsed)}`)
      Text(`宫已用:${digitsText(hint.info.boxUsed)}`)
      Text(`剩余候选:${hint.value}`).fontSize(26).fontColor('#445F97')
      Button('应用当前提示').backgroundColor('#445F97').onClick(() => { this.applyHint(hint); })
    }.width('100%')
  }
  @Builder
  hintPanel(width: number) {
    Column({space:12}) {
      Text('候选增量刷新与缓存失效').fontSize(22)
      Text(`单格唯一候选:${this.hints.length}处`)
      Flex({direction:FlexDirection.Row,wrap:FlexWrap.Wrap}) {
        ForEach(this.hints,(hint: SingleHint) => {
          Button(hintText(hint)).fontSize(12).width((width-56)/3).margin(4)
            .backgroundColor(hint.index===this.hintIndex ? '#445F97' : '#A8B8D7')
            .onClick(() => { this.hintIndex=hint.index; })
        },(hint: SingleHint) => `${hint.index}`)
      }.width('100%')
      ForEach(this.hints.filter((hint: SingleHint) => hint.index===this.hintIndex),(hint: SingleHint) => {
        this.hintDetail(hint)
      },(hint: SingleHint) => `${hint.boardKey}:${hint.index}`)
      if (this.hints.length===0) { Text('当前没有单格唯一候选') }
      Text(`已填格:${this.history.state.board.filter((value: number) => value!==0).length} · 空格:${this.history.state.board.filter((value: number) => value===0).length}`)
      Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
    }.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
  }
  @Builder
  inputPanel(width: number) {
    Column({space:12}) {
      Text('目标格输入').fontSize(22)
      TextInput({text:this.rowText,placeholder:'行'})
        .onChange((value: string) => { this.rowText=value; this.status='输入待查询'; })
      TextInput({text:this.colText,placeholder:'列'})
        .onChange((value: string) => { this.colText=value; this.status='输入待查询'; })
      TextInput({text:this.digitText,placeholder:'填入0至9,0清空'})
        .onChange((value: string) => { this.digitText=value; this.status='输入待提交'; })
      Button('提交填数').backgroundColor('#445F97').onClick(() => { this.submit(); })
      Button('查询候选').backgroundColor('#445F97').onClick(() => { this.query(); })
      Text(this.status)
      Text(`已填格:${this.history.state.board.filter((value: number) => value!==0).length}`)
      Text(`空格:${this.history.state.board.filter((value: number) => value===0).length}`)
    }.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
  }
  @Builder
  resultPanel(width: number) {
    Column({space:14}) {
      Text(`目标:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
      Text(`当前格值:${this.history.state.board[this.selected]}`)
      Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
      Text(`有效修改:${this.history.cursor}`)
      if (this.history.state.board[this.selected]===0) {
        Text(`行已用:${digitsText(this.info.rowUsed)}`)
        Text(`列已用:${digitsText(this.info.colUsed)}`)
        Text(`宫已用:${digitsText(this.info.boxUsed)}`)
      }
      Text(this.candidateText).fontSize(26).fontColor('#445F97')
      Button('恢复题面').onClick(() => { this.reset(); })
    }.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
  }
  build() {
    Scroll() {
      Column({space:16}) {
        Text('数独候选台').fontSize(26).fontWeight(FontWeight.Bold)
        Text('候选增量刷新与缓存失效')
        if (this.areaWidth>=840) {
          Row({space:16}) {
            Column({space:16}) {
              this.cachePanel((this.areaWidth-56)/2)
              this.searchPanel((this.areaWidth-56)/2)
              this.historyPanel((this.areaWidth-56)/2)
              this.hintPanel((this.areaWidth-56)/2)
            }
            Column({space:16}) {
              this.inputPanel((this.areaWidth-56)/2)
              this.resultPanel((this.areaWidth-56)/2)
            }
          }.alignItems(VerticalAlign.Top)
        } else {
          this.cachePanel(this.areaWidth-40)
          this.searchPanel(this.areaWidth-40)
          this.historyPanel(this.areaWidth-40)
          this.hintPanel(this.areaWidth-40)
          this.inputPanel(this.areaWidth-40)
          this.resultPanel(this.areaWidth-40)
        }
      }.width('100%').padding(20)
    }.width('100%').height('100%').backgroundColor('#F1F4FA')
      .onAreaChange((oldArea: Area,newArea: Area) => {
        const width: number = Number(newArea.width);
        if (Number.isFinite(width) && width>40 && width!==this.areaWidth) this.areaWidth=width;
      })
  }
}

增量缓存服务与开发预览

页面在局部变量中准备新历史、新缓存和新提示,三者都成功后再发布。查询候选直接读取当前缓存,清空或历史恢复后也从新缓存取得目标解释。窗口宽度回调只更新布局宽度,不重建缓存,不把局部刷新统计恢复为初始值。

恢复题面按钮建立新的初始历史与完整缓存,这属于明确的全量基线重建。普通撤销重做则比较恢复前后的题面,走相同增量入口。无需把旧候选数组放进历史记录,也无需为了恢复摘要再维护一组候选历史游标。

分开显示三种统计

变化格数表示前后数字不同的位置数量,影响格数表示需要重新考虑的区域并集,重算空格表示实际调用候选查询的位置数量。三个数值描述不同阶段,不能把影响格数直接写成候选重算次数,也不能用缓存空格总量代替本次工作量。

默认在一行三列填入一,变化格数为一,影响格数为二十一,重算空格为十四。该目标变为已填,缓存空格总量从五十一降为五十,已填格为三十一。目标自身进入影响范围,但它在新题面中已有数字,因此没有候选查询。

手机上的刷新范围与候选缓存摘要

对相同题面再次调用更新,变化格数、影响格数与重算空格均应为零。缓存依旧返回独立结果对象,但不需要重新查询候选。若页面把一次无变化提交也显示为二十一格影响,检查变化格比较是否确实使用了前后数字,而不是按钮点击位置。

与完整重算逐格对照

增量路径最重要的检查是逐个空格与queryCandidates完整查询比较,四个数组都应一致。只核对候选数字还不够,因为解释来源可能过期。已有数字位置应为空项,缓存中的棋盘副本应与新题面逐格相等,提示列表也应与原findSingleHints的结果一致。

可以从初始题面的每个空格出发,对其每个合法候选分别提交,再做增量与全量比较。这样能够覆盖跨宫边界、行列交叉和不同同伴分布,而不只依赖默认一行三列这一个样本。多格变化则验证标记数组确实对区域并集去重。

清空刚填写的数字后,目标格应重新具有候选,同行列宫的解释也要恢复。撤销与重做可以反复经过同一个数字变化,缓存结果只由当前棋盘决定,不能因为某格曾经填过一就永久排除这个数字。

以正确性约束刷新范围

遇到少刷新,先检查变化格集合,再检查它们的行列宫并集;遇到候选正确而解释旧,检查是否仅复制了values;遇到旧缓存随新查询变化,检查四个子数组是否都经过复制。每层数据都有独立含义,定位时不必从界面文本反推集合。

本篇减少的是候选查询的重复工作,题面校验、冲突检查和提示列表遍历仍保留各自职责。缓存将变化事实转换为局部失效范围,再用纯查询服务补齐结果;宽窄屏页面共享同一基线,下一章增加键盘输入和可访问性入口时,也能继续走相同提交与刷新链路。

相关资料

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐