Files
river_crossing_puzzle_gener…/river_puzzle_guided.py
T

248 lines
9.1 KiB
Python

#!/usr/bin/env python3
"""Constraint-guided river-crossing puzzle generator (Python 3.10+, stdlib only).
Usage:
python river_puzzle_guided.py 6 2
python river_puzzle_guided.py 6 2 --seed 42 --attempts 300
The generator proposes a route first, then synthesizes conditional safety rules
to block deviations. It independently checks the full state graph and accepts
only a unique shortest solution matching the proposed route.
A rule "A and B require C" means that an unattended bank containing A and B
is unsafe unless C is also on that bank. Empty-bank and single-animal rules
are deliberately not generated.
"""
from __future__ import annotations
import argparse
import itertools
import random
import sys
from collections import deque
from dataclasses import dataclass
ANIMALS = [
"monkey", "dog", "cat", "tortoise", "lizard", "bird", "rabbit",
"fox", "goat", "chicken", "wolf", "duck", "snake", "hamster",
"raccoon", "parrot",
]
State = tuple[int, int] # (right-bank animal bitmask, boat bank: 0=left, 1=right)
@dataclass(frozen=True)
class Rule:
trigger: int
guardian: int
def violated(self, bank: int) -> bool:
return (bank & self.trigger) == self.trigger and not (bank & self.guardian)
def describe(self, names: list[str]) -> str:
trigger_names = [names[i] for i in range(len(names)) if self.trigger & (1 << i)]
guardian_name = names[self.guardian.bit_length() - 1]
return (
f"The {' and '.join(trigger_names)} can be left together unsupervised "
f"only if the {guardian_name} is also present."
)
def unsafe(bank: int, rules: list[Rule]) -> bool:
return any(rule.violated(bank) for rule in rules)
def legal_moves(state: State, n: int, capacity: int, rules: list[Rule]):
right, boat = state
all_mask = (1 << n) - 1
available = (all_mask ^ right) if boat == 0 else right
bits = [1 << i for i in range(n) if available & (1 << i)]
cargoes = [0]
for size in range(1, min(capacity, len(bits)) + 1):
cargoes.extend(sum(combo) for combo in itertools.combinations(bits, size))
for cargo in cargoes:
if boat == 0:
new_right, new_boat = right | cargo, 1
unattended = all_mask ^ new_right
else:
new_right, new_boat = right & ~cargo, 0
unattended = new_right
if not unsafe(unattended, rules):
yield (new_right, new_boat), cargo
def solve(n: int, capacity: int, rules: list[Rule]):
all_mask = (1 << n) - 1
start: State = (0, 0)
goal: State = (all_mask, 1)
dist = {start: 0}
ways = {start: 1}
parent: dict[State, State | None] = {start: None}
cargo_to: dict[State, int] = {}
queue = deque([start])
while queue:
state = queue.popleft()
if state == goal:
continue
for nxt, cargo in legal_moves(state, n, capacity, rules):
nd = dist[state] + 1
if nxt not in dist:
dist[nxt] = nd
ways[nxt] = ways[state]
parent[nxt] = state
cargo_to[nxt] = cargo
queue.append(nxt)
elif dist[nxt] == nd:
ways[nxt] = min(2, ways[nxt] + ways[state])
if goal not in dist:
return None
states = []
cur: State | None = goal
while cur is not None:
states.append(cur)
cur = parent[cur]
states.reverse()
moves = [(states[i - 1], states[i], cargo_to[states[i]]) for i in range(1, len(states))]
return dist[goal], ways[goal], moves
def route_for(order: list[int]):
"""One animal outbound per trip; empty return except after final delivery."""
right = 0
boat = 0
route = []
for pos, animal in enumerate(order):
before = (right, boat)
right |= 1 << animal
boat = 1
route.append((before, (right, boat), 1 << animal))
if pos < len(order) - 1:
before = (right, boat)
boat = 0
route.append((before, (right, boat), 0))
return route
def unattended_after(state: State, n: int) -> int:
right, boat = state
all_mask = (1 << n) - 1
return (all_mask ^ right) if boat == 1 else right
def synthesize(n: int, capacity: int, rng: random.Random, attempts: int):
if n < 3:
raise ValueError("M must be at least 3 for conditional rules.")
if not 1 <= capacity < n:
raise ValueError("Boat capacity C must satisfy 1 <= C < M.")
if n > 10:
raise ValueError("Exact state-space verification is limited to M <= 10.")
for _attempt in range(attempts):
order = list(range(n))
rng.shuffle(order)
route = route_for(order)
route_states = [route[0][0]] + [move[1] for move in route]
next_on_route = {route_states[i]: route_states[i + 1]
for i in range(len(route_states) - 1)}
safe_banks = {unattended_after(s, n) for s in route_states[1:]}
rules: list[Rule] = []
# Candidate rules must preserve every unattended bank on the target route.
candidates = []
for size in range(2, n):
for trigger_indices in itertools.combinations(range(n), size):
trigger = sum(1 << i for i in trigger_indices)
for guardian in range(n):
if trigger & (1 << guardian):
continue
rule = Rule(trigger, 1 << guardian)
if all(not rule.violated(bank) for bank in safe_banks):
candidates.append(rule)
rng.shuffle(candidates)
# Add a rule that blocks an off-route successor. Recheck after every rule.
for _ in range(2 ** (2 * n)):
result = solve(n, capacity, rules)
if result is None:
break
distance, ways, moves = result
intended_length = len(route)
actual_states = [route_states[0]] + [m[1] for m in moves]
if distance == intended_length and ways == 1 and actual_states == route_states:
return rules, route, order
added = False
for state in route_states[:-1]:
intended_next = next_on_route[state]
for nxt, _cargo in legal_moves(state, n, capacity, rules):
if nxt == intended_next:
continue
bad_bank = unattended_after(nxt, n)
for candidate in candidates:
if candidate in rules:
continue
if candidate.violated(bad_bank):
rules.append(candidate)
added = True
break
if added:
break
if added:
break
if not added:
break
raise RuntimeError(
f"No verified puzzle found after {attempts} proposed routes. "
"Try a different --seed, increase --attempts, or change M/C."
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("M", type=int, help="number of animals")
parser.add_argument("C", type=int, help="boat capacity; must be less than M")
parser.add_argument("--seed", type=int, default=None, help="reproducible random seed")
parser.add_argument("--attempts", type=int, default=100, help="proposed routes to try")
args = parser.parse_args()
if args.attempts < 1:
parser.error("--attempts must be positive")
try:
names = ANIMALS[:args.M]
if args.M > len(names):
names += [f"animal_{i + 1}" for i in range(len(names), args.M)]
rules, route, order = synthesize(args.M, args.C, random.Random(args.seed), args.attempts)
result = solve(args.M, args.C, rules)
assert result is not None
except (ValueError, RuntimeError) as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
distance, ways, _ = result
print("=" * 64)
print("RIVER-CROSSING PUZZLE")
print("=" * 64)
print(f"Animals: {', '.join(names)}")
print(f"Boat capacity: {args.C} animal(s), plus the supervisor")
print("\nSAFETY RULES")
for i, rule in enumerate(rules, 1):
print(f"{i}. {rule.describe(names)}")
print("\nPUZZLE")
print("Move all animals from the left bank to the right bank. The human supervisor")
print(f"must accompany every crossing; the boat carries at most {args.C} animals.")
print("Whenever a bank is left without the supervisor, all safety rules must hold.")
print("The boat may return empty.")
print("\nSOLUTION")
print(f"{distance} crossings; unique shortest solution: {'yes' if ways == 1 else 'NO'}")
for i, (_before, after, cargo) in enumerate(route, 1):
direction = "left → right" if after[1] == 1 else "right → left"
cargo_names = [names[j] for j in range(args.M) if cargo & (1 << j)]
print(f"{i:2}. {direction}: {', '.join(cargo_names) if cargo_names else '(empty boat)'}")
print("\nVerification: the proposed route matches the unique shortest path found by BFS.")
return 0
if __name__ == "__main__":
raise SystemExit(main())