Files
2026-11-02 10:06:32 +01:00

454 lines
15 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'puzzle.dart';
enum ThinkingRule { direct, comparison, assumption }
enum ThinkingStatus { solved, inconsistent, nonUnique, depthLimit, nodeLimit }
/// A checkable reason for rejecting a hypothetical mark. A split rejects both
/// values of [cell]; a leaf names the clue contradiction after propagation.
class ContradictionProof {
const ContradictionProof(this.reason, {this.cell, this.branches = const []});
final String reason;
final int? cell;
final List<ContradictionProof> branches;
Map<String, Object?> toJson() => {
'reason': reason,
if (cell != null) 'splitCell': cell,
if (branches.isNotEmpty)
'branches': branches.map((p) => p.toJson()).toList(),
};
}
class ThinkingStep {
const ThinkingStep({
required this.rule,
required this.clues,
required this.marks,
required this.explanation,
required this.cellsCompared,
this.assumptionDepth = 0,
this.rejectedValue,
this.proof,
});
final ThinkingRule rule;
final List<String> clues;
// Solver encoding: 0 = dark, 1 = lit. Indices are zero-based.
final Map<int, int> marks;
final String explanation;
final int cellsCompared, assumptionDepth;
final int? rejectedValue;
final ContradictionProof? proof;
Map<String, Object?> toJson() => {
'rule': rule.name,
'clues': clues,
'marks': [
for (final entry in marks.entries)
{'cell': entry.key, 'value': entry.value},
],
'explanation': explanation,
'cellsCompared': cellsCompared,
'assumptionDepth': assumptionDepth,
if (rejectedValue != null) 'rejectedValue': rejectedValue,
if (proof != null) 'contradictionProof': proof!.toJson(),
};
}
class ThinkingRound {
const ThinkingRound(this.steps);
final List<ThinkingStep> steps;
int get newCells => steps.fold(0, (sum, step) => sum + step.marks.length);
Map<String, Object> toJson() => {
'newCells': newCells,
'steps': steps.map((s) => s.toJson()).toList(),
};
}
class ThinkingReport {
const ThinkingReport({
required this.status,
required this.cells,
required this.rounds,
required this.givens,
required this.solutionCount,
required this.searchNodes,
required this.maxLookahead,
required this.message,
});
final ThinkingStatus status;
final List<int> cells;
final List<ThinkingRound> rounds;
final int givens, searchNodes, maxLookahead;
// null means the bounded solution check did not finish; 2 means at least two.
final int? solutionCount;
final String message;
Iterable<ThinkingStep> get steps => rounds.expand((r) => r.steps);
int get resolvedCells => cells.where((v) => v >= 0).length - givens;
int get initialDirectMoves => rounds.isEmpty
? 0
: rounds.first.steps
.where((s) => s.rule == ThinkingRule.direct)
.fold(0, (sum, s) => sum + s.marks.length);
int get comparisonSteps =>
steps.where((s) => s.rule == ThinkingRule.comparison).length;
int get assumptionSteps =>
steps.where((s) => s.rule == ThinkingRule.assumption).length;
int get maxAssumptionDepthUsed => steps.fold(
0,
(depth, s) => s.assumptionDepth > depth ? s.assumptionDepth : depth,
);
int? get lookaheadDepth =>
status == ThinkingStatus.solved ? maxAssumptionDepthUsed : null;
int get maxCellsCompared => steps.fold(
0,
(count, s) => s.cellsCompared > count ? s.cellsCompared : count,
);
int get narrowestRound => rounds.isEmpty
? 0
: rounds.map((r) => r.newCells).reduce((a, b) => a < b ? a : b);
Map<String, Object?> toJson() => {
'status': status.name,
'message': message,
'solutionCountCappedAtTwo': solutionCount,
'cellCount': cells.length,
'givens': givens,
'resolvedCells': resolvedCells,
'initialDirectMoves': initialDirectMoves,
'deductionRounds': rounds.length,
'comparisonSteps': comparisonSteps,
'assumptionSteps': assumptionSteps,
'maxAssumptionDepthUsed': maxAssumptionDepthUsed,
'lookaheadDepth': lookaheadDepth,
'lookaheadLimit': maxLookahead,
'maxCellsCompared': maxCellsCompared,
'narrowestRound': narrowestRound,
'searchNodes': searchNodes,
'remainingCells': [
for (var i = 0; i < cells.length; i++)
if (cells[i] < 0) i,
],
'rounds': rounds.map((r) => r.toJson()).toList(),
};
}
class _Scan {
const _Scan(this.steps, [this.error]);
final List<ThinkingStep> steps;
final String? error;
}
class _Closure {
const _Closure(this.cells, this.error);
final List<int> cells;
final String? error;
bool get solved => error == null && !cells.contains(-1);
}
class _NodeLimit implements Exception {}
/// A reproducible reasoning model, not a psychometric measure. Ordinary rules
/// are applied in parallel from an unchanged snapshot. When stalled, the model
/// tries contradiction proofs of increasing assumption depth, never consulting
/// the authored picture/answer. All cells can be written down between rounds.
class ThinkingAnalyzer {
ThinkingAnalyzer(this.cellCount, List<Constraint> constraints)
: constraints = List.unmodifiable(constraints) {
if (cellCount < 1 || cellCount > 100) {
throw ArgumentError('Expected 1–100 cells');
}
for (final c in constraints) {
if (c.cells.toSet().length != c.cells.length ||
c.cells.any((i) => i < 0 || i >= cellCount)) {
throw ArgumentError('Invalid cells in ${c.name}');
}
}
}
final int cellCount;
final List<Constraint> constraints;
int _nodes = 0, _limit = 0;
void _visit() {
if (_nodes >= _limit) throw _NodeLimit();
_nodes++;
}
_Scan _scan(List<int> known) {
final unknown = <Set<int>>[], need = <int>[];
final candidates = <int, ThinkingStep>{};
String? conflict;
void propose(ThinkingStep step) {
for (final mark in step.marks.entries) {
final old = candidates[mark.key];
if (old != null && old.marks[mark.key] != mark.value) {
conflict = 'Clues force both lit and dark at cell ${mark.key}.';
} else if (old == null ||
step.clues.length < old.clues.length ||
step.clues.length == old.clues.length &&
step.cellsCompared < old.cellsCompared) {
candidates[mark.key] = step;
}
}
}
for (final c in constraints) {
final empty = c.cells.where((i) => known[i] < 0).toSet();
final remaining = c.total - c.cells.where((i) => known[i] == 1).length;
unknown.add(empty);
need.add(remaining);
if (remaining < 0 || remaining > empty.length) {
return _Scan(
[],
'${c.name} needs $remaining lights in ${empty.length} unmarked cells.',
);
}
if (empty.isNotEmpty && (remaining == 0 || remaining == empty.length)) {
propose(
ThinkingStep(
rule: ThinkingRule.direct,
clues: [c.name],
marks: {for (final i in empty) i: remaining == 0 ? 0 : 1},
explanation:
'${c.name} needs $remaining more lights in ${empty.length} unmarked cells.',
cellsCompared: empty.length,
),
);
}
}
// Prefer writing down every available simple deduction before asking the
// player to compare two clues. Comparisons are used only at a simple-rule stall.
if (candidates.isEmpty) {
for (var a = 0; a < constraints.length; a++) {
for (var b = a + 1; b < constraints.length; b++) {
if (unknown[a].intersection(unknown[b]).isEmpty) continue;
final onlyA = unknown[a].difference(unknown[b]);
final onlyB = unknown[b].difference(unknown[a]);
final diff = need[a] - need[b];
if (diff > onlyA.length || diff < -onlyB.length) {
return _Scan(
[],
'Comparing ${constraints[a].name} and ${constraints[b].name} leaves an impossible difference of $diff lights.',
);
}
if (onlyA.isEmpty && onlyB.isEmpty ||
diff != onlyA.length && diff != -onlyB.length) {
continue;
}
final valueA = diff == onlyA.length ? 1 : 0;
propose(
ThinkingStep(
rule: ThinkingRule.comparison,
clues: [constraints[a].name, constraints[b].name],
marks: {
for (final i in onlyA) i: valueA,
for (final i in onlyB) i: 1 - valueA,
},
explanation:
'Cancel shared unmarked cells in ${constraints[a].name} (${need[a]} lights left) and ${constraints[b].name} (${need[b]} left). Difference: $diff.',
cellsCompared: unknown[a].union(unknown[b]).length,
),
);
}
}
}
if (conflict != null) return _Scan([], conflict);
// Keep each cell's simplest reason, and merge cells with the same reason.
final selected = <ThinkingStep, Map<int, int>>{};
for (final entry in candidates.entries) {
(selected[entry.value] ??= {})[entry.key] = entry.value.marks[entry.key]!;
}
return _Scan([
for (final entry in selected.entries)
ThinkingStep(
rule: entry.key.rule,
clues: entry.key.clues,
marks: entry.value,
explanation: entry.key.explanation,
cellsCompared: entry.key.cellsCompared,
),
]);
}
_Closure _close(List<int> initial, [List<ThinkingRound>? rounds]) {
final known = List<int>.of(initial);
while (true) {
final scan = _scan(known);
if (scan.error != null || scan.steps.isEmpty) {
return _Closure(known, scan.error);
}
rounds?.add(ThinkingRound(scan.steps));
for (final step in scan.steps) {
for (final mark in step.marks.entries) {
known[mark.key] = mark.value;
}
}
}
}
List<int> _choices(List<int> known) {
final unknown = [
for (var i = 0; i < cellCount; i++)
if (known[i] < 0) i,
];
final degree = [
for (var i = 0; i < cellCount; i++)
constraints.where((c) => c.cells.contains(i)).length,
];
unknown.sort((a, b) {
final order = degree[b].compareTo(degree[a]);
return order == 0 ? a.compareTo(b) : order;
});
return unknown;
}
int _count(List<int> initial) {
_visit();
final state = _close(initial);
if (state.error != null) return 0;
if (state.solved) return 1;
final cell = _choices(state.cells).first;
final dark = List<int>.of(state.cells)..[cell] = 0;
final count = _count(dark);
if (count >= 2) return 2;
final light = List<int>.of(state.cells)..[cell] = 1;
final total = count + _count(light);
return total > 2 ? 2 : total;
}
ContradictionProof? _refute(List<int> initial, int extraDepth) {
_visit();
final state = _close(initial);
if (state.error != null) return ContradictionProof(state.error!);
if (state.solved || extraDepth == 0) return null;
// Try every split variable. A refutation requires BOTH branches to fail;
// finding one satisfying or unresolved branch is never a contradiction.
for (final cell in _choices(state.cells)) {
final dark = _refute(
List<int>.of(state.cells)..[cell] = 0,
extraDepth - 1,
);
if (dark == null) continue;
final light = _refute(
List<int>.of(state.cells)..[cell] = 1,
extraDepth - 1,
);
if (light != null) {
return ContradictionProof(
'Both values of cell $cell contradict the clues.',
cell: cell,
branches: [dark, light],
);
}
}
return null;
}
ThinkingStep? _lookAhead(List<int> known, int maxDepth) {
for (var depth = 1; depth <= maxDepth; depth++) {
for (final cell in _choices(known)) {
for (final value in [0, 1]) {
final proof = _refute(List<int>.of(known)..[cell] = value, depth - 1);
if (proof != null) {
return ThinkingStep(
rule: ThinkingRule.assumption,
clues: const [],
marks: {cell: 1 - value},
explanation:
'Assume cell $cell is ${value == 1 ? 'lit' : 'dark'}. Propagation and at most ${depth - 1} additional nested assumptions prove a contradiction, so it must be ${value == 1 ? 'dark' : 'lit'}.',
cellsCompared: 0,
assumptionDepth: depth,
rejectedValue: value,
proof: proof,
);
}
}
}
}
return null;
}
ThinkingReport analyze(
List<int> initial, {
int maxLookahead = 2,
int nodeLimit = 50000,
}) {
if (initial.length != cellCount || initial.any((v) => v < -1 || v > 1)) {
throw ArgumentError(
'Use -1 (unmarked), 0 (dark), 1 (lit), one value per cell',
);
}
if (maxLookahead < 0 || maxLookahead > 3 || nodeLimit < 1) {
throw ArgumentError('Lookahead must be 0–3; node limit must be positive');
}
_nodes = 0;
_limit = nodeLimit;
final rounds = <ThinkingRound>[];
var state = _close(initial, rounds);
int? solutions;
ThinkingReport report(ThinkingStatus status, String message) =>
ThinkingReport(
status: status,
cells: List.unmodifiable(state.cells),
rounds: List.unmodifiable(rounds),
givens: initial.where((v) => v >= 0).length,
solutionCount: solutions,
searchNodes: _nodes,
maxLookahead: maxLookahead,
message: message,
);
if (state.error != null) {
solutions = 0;
return report(ThinkingStatus.inconsistent, state.error!);
}
if (state.solved) {
solutions = 1;
return report(
ThinkingStatus.solved,
'Solved by visible deductions; no hypothetical lookahead needed.',
);
}
try {
// The solution counter validates uniqueness only. It never feeds any
// answer cells back into the human-style deduction or lookahead path.
solutions = _count(state.cells);
if (solutions == 0) {
return report(
ThinkingStatus.inconsistent,
'No completion satisfies all clues.',
);
}
if (solutions > 1) {
return report(
ThinkingStatus.nonUnique,
'Multiple completions satisfy the clues; there is no single answer to deduce.',
);
}
while (!state.solved) {
final step = _lookAhead(state.cells, maxLookahead);
if (step == null) {
return report(
ThinkingStatus.depthLimit,
'The model stalls after testing lookahead through depth $maxLookahead. This is not proof that a human must guess.',
);
}
rounds.add(ThinkingRound([step]));
final next = List<int>.of(state.cells);
for (final mark in step.marks.entries) {
next[mark.key] = mark.value;
}
state = _close(next, rounds);
if (state.error != null) {
return report(ThinkingStatus.inconsistent, state.error!);
}
}
return report(
ThinkingStatus.solved,
'Solved with contradiction-based hypothetical lookahead on this deterministic reasoning path.',
);
} on _NodeLimit {
return report(
ThinkingStatus.nodeLimit,
'Stopped at the $nodeLimit-node search budget; unresolved depth is unknown, not zero.',
);
}
}
}