Files
logic-puzzle/lib/domain/puzzle.dart
T
2026-11-14 08:55:48 +01:00

482 lines
15 KiB
Dart
Raw 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 'dart:math' as math;
enum Difficulty {
easy('Easy', 'Short deductions. A gentle place to begin.'),
medium('Medium', 'Link deductions across rows and columns.'),
hard('Hard', 'Follow longer chains to uncover the pattern.');
const Difficulty(this.label, this.description);
final String label, description;
String get stored => name.toUpperCase();
static Difficulty fromStored(String value) =>
values.firstWhere((d) => d.stored == value, orElse: () => easy);
static Difficulty fromRounds(int n) => n <= 2
? easy
: n <= 4
? medium
: hard;
}
/// Explicit Java-compatible PRNG keeps generated boards stable across platforms.
class JavaRandom {
JavaRandom(BigInt seed) : _seed = (seed ^ _multiplier) & _mask;
static final _multiplier = BigInt.from(0x5DEECE66D);
static final _mask = (BigInt.one << 48) - BigInt.one;
BigInt _seed;
int next(int bits) {
_seed = (_seed * _multiplier + BigInt.from(11)) & _mask;
return (_seed >> (48 - bits)).toInt();
}
int nextInt(int bound) {
if ((bound & -bound) == bound) {
return ((BigInt.from(bound) * BigInt.from(next(31))) >> 31).toInt();
}
while (true) {
final bits = next(31), value = bits % bound;
if (bits - value + bound - 1 < 0x80000000) return value;
}
}
BigInt nextLong() {
final high = BigInt.from(next(32)).toSigned(32);
final low = BigInt.from(next(32)).toSigned(32);
return ((high << 32) + low).toSigned(64);
}
void shuffle<T>(List<T> list) {
for (var i = list.length; i > 1; i--) {
final j = nextInt(i), old = list[i - 1];
list[i - 1] = list[j];
list[j] = old;
}
}
}
class Region {
const Region(this.label, this.top, this.left, this.height, this.width);
final String label;
final int top, left, height, width;
bool contains(int index, int size) =>
index ~/ size >= top &&
index ~/ size < top + height &&
index % size >= left &&
index % size < left + width;
}
class Constraint {
Constraint(this.cells, this.total, this.name, {this.equal = false});
final List<int> cells;
final int total;
final String name;
final bool equal;
}
/// Exactly one of the two cells is lit.
class LanternPair {
const LanternPair(this.first, this.second);
final int first, second;
bool contains(int cell) => cell == first || cell == second;
}
class Hint {
const Hint(this.cell, this.value, this.explanation);
final int cell, value;
final String explanation;
}
class Analysis {
const Analysis(this.solved, this.areaDeductions, this.cells);
final bool solved;
final int areaDeductions;
final List<int> cells;
}
class LogicSolver {
LogicSolver(this.cellCount, this.constraints);
final int cellCount;
final List<Constraint> constraints;
int _need(Constraint c, List<int> known) =>
c.total - c.cells.where((i) => known[i] == 1).length;
List<int> _unknown(Constraint c, List<int> known) =>
c.cells.where((i) => known[i] < 0).toList();
int _singles(List<int> known) {
var changes = 0;
for (final c in constraints) {
if (c.equal) {
final a = c.cells[0], b = c.cells[1];
if (known[a] >= 0 && known[b] >= 0 && known[a] != known[b]) return -1;
if (known[a] >= 0 && known[b] < 0) {
known[b] = known[a];
changes++;
}
if (known[b] >= 0 && known[a] < 0) {
known[a] = known[b];
changes++;
}
continue;
}
final need = _need(c, known), unknown = _unknown(c, known);
if (need < 0 || need > unknown.length) return -1;
if (unknown.isEmpty || (need != 0 && need != unknown.length)) continue;
for (final i in unknown) {
known[i] = need == 0 ? 0 : 1;
changes++;
}
}
return changes;
}
Hint? nextHint(List<int> known) {
for (final c in constraints) {
if (c.equal) {
final a = c.cells[0], b = c.cells[1];
if (known[a] >= 0 && known[b] < 0) {
return Hint(
b,
known[a],
'The mirrored cells match: both are lit or both are crossed out.',
);
}
if (known[b] >= 0 && known[a] < 0) {
return Hint(
a,
known[b],
'The mirrored cells match: both are lit or both are crossed out.',
);
}
continue;
}
final need = _need(c, known), unknown = _unknown(c, known);
if (need < 0 || need > unknown.length) return null;
if (unknown.isNotEmpty && (need == 0 || need == unknown.length)) {
if (c.name.startsWith('Footprint trail')) {
return Hint(
unknown.first,
need == 0 ? 0 : 1,
'Two footprints must be lit and touch. The middle footprint is lit, and exactly one end is lit.',
);
}
if (c.name == 'Lantern pair') {
return Hint(
unknown.first,
need == 0 ? 0 : 1,
need == 0
? 'The other lantern is lit, so this lantern must be crossed out. Exactly one lantern in the pair is lit.'
: 'The other lantern is crossed out, so this lantern must be lit. Exactly one lantern in the pair is lit.',
);
}
return Hint(
unknown.first,
need == 0 ? 0 : 1,
need == 0
? '${c.name} already has all its lights. Every remaining cell in it must be crossed out.'
: '${c.name} needs $need more lights and has exactly ${unknown.length} empty cells. They must all be lit.',
);
}
}
for (var a = 0; a < constraints.length; a++) {
final first = constraints[a];
if (first.equal) continue;
for (var b = a + 1; b < constraints.length; b++) {
final second = constraints[b];
if (second.equal) continue;
final onlyA = _unknown(
first,
known,
).where((i) => !second.cells.contains(i)).toList();
final onlyB = _unknown(
second,
known,
).where((i) => !first.cells.contains(i)).toList();
final needA = _need(first, known),
needB = _need(second, known),
diff = needA - needB;
if (onlyA.isEmpty && onlyB.isEmpty ||
(diff != onlyA.length && diff != -onlyB.length)) {
continue;
}
final valueA = diff == onlyA.length ? 1 : 0;
final explanation =
'Compare ${first.name} ($needA more lights) with ${second.name} ($needB more). Shared empty cells cancel. The difference forces the cells outside their overlap.';
return onlyA.isNotEmpty
? Hint(onlyA.first, valueA, explanation)
: Hint(onlyB.first, 1 - valueA, explanation);
}
}
return null;
}
Analysis analyze(List<int> initial, {bool useAreas = true}) {
final known = List<int>.of(initial);
var areas = 0;
while (true) {
final changed = _singles(known);
if (changed < 0) return Analysis(false, areas, known);
if (changed > 0) continue;
if (useAreas) {
final hint = nextHint(known);
if (hint != null) {
known[hint.cell] = hint.value;
areas++;
continue;
}
}
return Analysis(!known.contains(-1), areas, known);
}
}
int countSolutions(List<int> initial) {
int search(List<int> known) {
int changed;
do {
changed = _singles(known);
if (changed < 0) return 0;
} while (changed > 0);
var choice = -1, degree = -1;
for (var i = 0; i < cellCount; i++) {
if (known[i] >= 0) continue;
final d = constraints.where((c) => c.cells.contains(i)).length;
if (d > degree) {
choice = i;
degree = d;
}
}
if (choice < 0) return 1;
final branch = List<int>.of(known)..[choice] = 0;
final count = search(branch);
if (count >= 2) return 2;
known[choice] = 1;
return math.min(2, count + search(known));
}
return search(List<int>.of(initial));
}
}
class Puzzle {
Puzzle(this.size, List<int> picture)
: solution = List<int>.of(picture),
given = List<bool>.filled(size * size, false) {
if (picture.length != size * size || picture.any((v) => v != 0 && v != 1)) {
throw ArgumentError('Invalid picture');
}
}
final int size;
final List<int> solution;
final List<bool> given;
final List<Region> regions = [];
final List<LanternPair> lanternPairs = [];
final List<LanternPair> mirrorPairs = [];
final List<List<int>> footprintTrails = [];
int? hiddenRow;
List<int> get rows => List.generate(
size,
(r) => List.generate(
size,
(c) => solution[r * size + c],
).reduce((a, b) => a + b),
);
List<int> get cols => List.generate(
size,
(c) => List.generate(
size,
(r) => solution[r * size + c],
).reduce((a, b) => a + b),
);
int regionTotal(Region r) => List.generate(
solution.length,
(i) => r.contains(i, size) ? solution[i] : 0,
).reduce((a, b) => a + b);
List<Constraint> get constraints => [
for (final trail in footprintTrails) ...[
Constraint([trail[1]], 1, 'Footprint trail centre'),
Constraint([trail[0], trail[2]], 1, 'Footprint trail ends'),
],
for (final pair in mirrorPairs)
Constraint([pair.first, pair.second], 0, 'Mirrored cells', equal: true),
for (final pair in lanternPairs)
Constraint([pair.first, pair.second], 1, 'Lantern pair'),
for (var l = 0; l < size; l++) ...[
Constraint(
List.generate(size, (p) => l * size + p),
rows[l],
'Row ${l + 1}',
),
Constraint(
List.generate(size, (p) => p * size + l),
cols[l],
'Column ${l + 1}',
),
],
for (final r in regions)
Constraint(
[
for (var y = r.top; y < r.top + r.height; y++)
for (var x = r.left; x < r.left + r.width; x++) y * size + x,
],
regionTotal(r),
'Area ${r.label}',
),
];
List<int> get initial =>
List.generate(solution.length, (i) => given[i] ? solution[i] : -1);
factory Puzzle.seeded(BigInt seed) {
final random = JavaRandom(seed);
final puzzle = Puzzle(5, List.generate(25, (_) => random.next(1)));
final order = List.generate(25, (i) => i);
random.shuffle(order);
for (final i in order) {
if (puzzle.countSolutions() == 1) break;
puzzle.given[i] = true;
}
return puzzle;
}
/// Stable 7×7 boards for daily and practice play. Remove fixed clues only
/// while a unique, deduction-solvable board within the requested grade remains.
static Puzzle generateSeven(BigInt seed, Difficulty difficulty) {
final random = JavaRandom(seed);
Puzzle? best;
for (var attempt = 0; attempt < 32; attempt++) {
final p = Puzzle(7, List.generate(49, (_) => random.next(1)));
p.given.fillRange(0, 49, true);
final order = List.generate(49, (i) => i);
random.shuffle(order);
for (final i in order) {
p.given[i] = false;
if (p.countSolutions() != 1 ||
!LogicSolver(49, p.constraints).analyze(p.initial).solved ||
p.difficulty.index > difficulty.index) {
p.given[i] = true;
}
}
best = p;
if (p.difficulty == difficulty) return p;
}
return best!;
}
static Puzzle generate(BigInt seed, Difficulty difficulty) {
final random = JavaRandom(seed);
for (var i = 0; i < 256; i++) {
final p = Puzzle.seeded(random.nextLong());
if (difficulty != Difficulty.easy) p._removeRedundant();
if (p.difficulty == difficulty) return p;
}
final p = Puzzle.seeded(BigInt.from(difficulty == Difficulty.hard ? 2 : 0));
if (difficulty != Difficulty.easy) p._removeRedundant();
final r = List.generate(5, (i) => i), c = List.generate(5, (i) => i);
random.shuffle(r);
random.shuffle(c);
final old = List<int>.of(p.solution), g = List<bool>.of(p.given);
for (var i = 0; i < 25; i++) {
final from = r[i ~/ 5] * 5 + c[i % 5];
p.solution[i] = old[from];
p.given[i] = g[from];
}
return p;
}
void _removeRedundant() {
for (var i = 0; i < 25; i++) {
if (!given[i]) continue;
given[i] = false;
if (countSolutions() != 1) given[i] = true;
}
}
int countSolutions() {
if (size != 5 || regions.isNotEmpty) {
return LogicSolver(solution.length, constraints).countSolutions(initial);
}
final rs = rows, cs = cols;
int search(int row, List<int> totals) {
if (row == 5) {
return List.generate(5, (i) => totals[i] == cs[i]).every((v) => v)
? 1
: 0;
}
var count = 0;
for (var mask = 0; mask < 32; mask++) {
var bits = 0;
for (var c = 0; c < 5; c++) {
bits += (mask >> c) & 1;
}
if (bits != rs[row]) continue;
final next = List<int>.of(totals);
var ok = true;
for (var c = 0; c < 5; c++) {
final v = (mask >> c) & 1, i = row * 5 + c;
next[c] += v;
if (given[i] && solution[i] != v ||
next[c] > cs[c] ||
next[c] + 4 - row < cs[c]) {
ok = false;
}
}
if (ok) count += search(row + 1, next);
if (count >= 2) return 2;
}
return count;
}
return search(0, List.filled(5, 0));
}
int get deductionRounds {
var known = initial;
var rounds = 0;
final lines = constraints;
while (known.contains(-1)) {
final next = List<int>.of(known);
var changed = false;
for (final c in lines) {
if (c.equal) {
final a = c.cells[0], b = c.cells[1];
if (known[a] >= 0 && known[b] < 0) {
next[b] = known[a];
changed = true;
}
if (known[b] >= 0 && known[a] < 0) {
next[a] = known[b];
changed = true;
}
continue;
}
final unknown = c.cells.where((i) => known[i] < 0).toList();
final need = c.total - c.cells.where((i) => known[i] == 1).length;
if (unknown.isNotEmpty && (need == 0 || need == unknown.length)) {
for (final i in unknown) {
next[i] = need == 0 ? 0 : 1;
changed = true;
}
}
}
if (!changed) throw StateError('Puzzle requires guessing');
known = next;
rounds++;
}
return rounds;
}
Difficulty get difficulty => Difficulty.fromRounds(deductionRounds);
bool solved(List<int> cells) =>
cells.length == solution.length &&
List.generate(
cells.length,
(i) => cells[i] == (solution[i] == 1 ? 1 : 2),
).every((v) => v);
}
int epochDay(DateTime date) =>
DateTime.utc(date.year, date.month, date.day).millisecondsSinceEpoch ~/
Duration.millisecondsPerDay;
int visibleStreak(int last, int count, int today) =>
last >= today - 1 ? count : 0;
int completedStreak(int last, int count, int day) => day <= last
? count
: last == day - 1
? count + 1
: 1;