my puzzle generator (river_puzzle_tg.py) + 3 written by ChatGPT
This commit is contained in:
+312
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
River-crossing puzzle generator and solver.
|
||||
|
||||
Examples:
|
||||
python river_puzzle.py 6 2
|
||||
python river_puzzle.py 7 2 --seed 42
|
||||
python river_puzzle.py 6 2 --attempts 5000
|
||||
|
||||
The generator accepts a puzzle only if:
|
||||
* a solution exists;
|
||||
* there is exactly one SHORTEST solution; and
|
||||
* the shortest solution uses at least M crossings.
|
||||
|
||||
Important: "unique solution" here means a unique shortest solution. If arbitrary
|
||||
detours and repeated crossings were allowed, a valid solution could be padded
|
||||
with pointless round trips, so literal uniqueness of every possible route is
|
||||
not a useful finite criterion.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import itertools
|
||||
import random
|
||||
import sys
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
BASE_ANIMALS = [
|
||||
"monkey", "dog", "cat", "tortoise", "lizard", "bird", "rabbit",
|
||||
"fox", "goat", "chicken", "wolf", "duck", "snake", "hamster",
|
||||
"raccoon", "parrot", "ferret", "hedgehog", "otter", "squirrel",
|
||||
]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Rule:
|
||||
"""A safety rule triggered by a set of animals on an unattended bank.
|
||||
|
||||
If required is empty, the trigger combination is forbidden.
|
||||
Otherwise, whenever all trigger animals are present, all required animals
|
||||
must also be present.
|
||||
"""
|
||||
trigger: tuple[int, ...]
|
||||
required: tuple[int, ...] = ()
|
||||
|
||||
def violated_by(self, bank_mask: int) -> bool:
|
||||
trigger_mask = sum(1 << i for i in self.trigger)
|
||||
if bank_mask & trigger_mask != trigger_mask:
|
||||
return False
|
||||
if not self.required:
|
||||
return True
|
||||
required_mask = sum(1 << i for i in self.required)
|
||||
return bank_mask & required_mask != required_mask
|
||||
|
||||
def describe(self, names: list[str]) -> str:
|
||||
trigger_names = [names[i] for i in self.trigger]
|
||||
if not self.required:
|
||||
if len(trigger_names) == 2:
|
||||
return f"The {trigger_names[0]} cannot be left unsupervised with the {trigger_names[1]}."
|
||||
return "These animals cannot be left unsupervised together: " + ", ".join(trigger_names) + "."
|
||||
required_names = [names[i] for i in self.required]
|
||||
if len(trigger_names) == 2 and len(required_names) == 1:
|
||||
return (
|
||||
f"The {' and '.join(trigger_names)} can be left together only if "
|
||||
f"the {required_names[0]} is also present."
|
||||
)
|
||||
return (
|
||||
f"If {', '.join(trigger_names)} are together unsupervised, "
|
||||
f"{' and '.join(required_names)} must also be present."
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SearchResult:
|
||||
distance: int
|
||||
ways: int
|
||||
path: list[tuple[int, int]] # (right-bank animal bitmask, boat/supervisor bank)
|
||||
|
||||
|
||||
def is_safe(bank_mask: int, rules: list[Rule]) -> bool:
|
||||
return not any(rule.violated_by(bank_mask) for rule in rules)
|
||||
|
||||
|
||||
def combinations_of_available(mask: int, capacity: int) -> Iterable[int]:
|
||||
"""Yield every subset of the available animals up to boat capacity."""
|
||||
bits = [i for i in range(mask.bit_length()) if mask & (1 << i)]
|
||||
for size in range(min(capacity, len(bits)) + 1):
|
||||
for combo in itertools.combinations(bits, size):
|
||||
subset = 0
|
||||
for i in combo:
|
||||
subset |= 1 << i
|
||||
yield subset
|
||||
|
||||
|
||||
def solve(names: list[str], capacity: int, rules: list[Rule]) -> SearchResult | None:
|
||||
"""BFS for a shortest solution and count shortest routes (capped at 2).
|
||||
|
||||
State = (animals on right bank, supervisor/boat bank); bank 0 is left,
|
||||
bank 1 is right. The bank without the supervisor must be safe after every
|
||||
crossing. Empty-boat crossings are allowed.
|
||||
"""
|
||||
n = len(names)
|
||||
all_animals = (1 << n) - 1
|
||||
start = (0, 0)
|
||||
goal = (all_animals, 1)
|
||||
|
||||
distance = {start: 0}
|
||||
ways = {start: 1}
|
||||
parent: dict[tuple[int, int], tuple[int, int] | None] = {start: None}
|
||||
queue = deque([start])
|
||||
|
||||
while queue:
|
||||
state = queue.popleft()
|
||||
right_mask, boat_bank = state
|
||||
d = distance[state]
|
||||
|
||||
if state == goal:
|
||||
continue
|
||||
|
||||
left_mask = all_animals ^ right_mask
|
||||
current_bank_mask = left_mask if boat_bank == 0 else right_mask
|
||||
|
||||
for carried in combinations_of_available(current_bank_mask, capacity):
|
||||
if boat_bank == 0:
|
||||
new_right = right_mask | carried
|
||||
new_boat_bank = 1
|
||||
unattended_bank = all_animals ^ new_right
|
||||
else:
|
||||
new_right = right_mask & ~carried
|
||||
new_boat_bank = 0
|
||||
unattended_bank = new_right
|
||||
|
||||
if not is_safe(unattended_bank, rules):
|
||||
continue
|
||||
|
||||
nxt = (new_right, new_boat_bank)
|
||||
nd = d + 1
|
||||
if nxt not in distance:
|
||||
distance[nxt] = nd
|
||||
ways[nxt] = ways[state]
|
||||
parent[nxt] = state
|
||||
queue.append(nxt)
|
||||
elif distance[nxt] == nd:
|
||||
ways[nxt] = min(2, ways[nxt] + ways[state])
|
||||
|
||||
if goal not in distance:
|
||||
return None
|
||||
|
||||
path = []
|
||||
cursor: tuple[int, int] | None = goal
|
||||
while cursor is not None:
|
||||
path.append(cursor)
|
||||
cursor = parent[cursor]
|
||||
path.reverse()
|
||||
return SearchResult(distance[goal], ways[goal], path)
|
||||
|
||||
|
||||
def random_rules(rng: random.Random, n: int) -> list[Rule]:
|
||||
"""Create a varied set of pair, conditional, and three-animal rules."""
|
||||
count = rng.randint(max(3, n), max(4, 2 * n))
|
||||
rules: list[Rule] = []
|
||||
seen: set[tuple[tuple[int, ...], tuple[int, ...]]] = set()
|
||||
|
||||
attempts = 0
|
||||
while len(rules) < count and attempts < count * 20:
|
||||
attempts += 1
|
||||
kind = rng.choices(["forbidden_pair", "conditional_pair", "forbidden_triple"],
|
||||
weights=[5, 4, 3], k=1)[0]
|
||||
if kind == "forbidden_pair":
|
||||
trigger = tuple(sorted(rng.sample(range(n), 2)))
|
||||
required: tuple[int, ...] = ()
|
||||
elif kind == "conditional_pair":
|
||||
a, b, guardian = rng.sample(range(n), 3)
|
||||
trigger = tuple(sorted((a, b)))
|
||||
required = (guardian,)
|
||||
else:
|
||||
trigger = tuple(sorted(rng.sample(range(n), 3)))
|
||||
required = ()
|
||||
|
||||
key = (trigger, required)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
rules.append(Rule(trigger, required))
|
||||
|
||||
return rules
|
||||
|
||||
|
||||
def render_solution(result: SearchResult, names: list[str]) -> list[str]:
|
||||
all_animals = (1 << len(names)) - 1
|
||||
lines = []
|
||||
for step, (right_mask, boat_bank) in enumerate(result.path[1:], start=1):
|
||||
previous_right, previous_boat = result.path[step - 1]
|
||||
moved_mask = right_mask ^ previous_right
|
||||
moved = [names[i] for i in range(len(names)) if moved_mask & (1 << i)]
|
||||
direction = "left → right" if boat_bank == 1 else "right → left"
|
||||
cargo = ", ".join(moved) if moved else "no animals (empty boat)"
|
||||
lines.append(f"{step:2}. Supervisor crosses {direction} with: {cargo}.")
|
||||
|
||||
return lines
|
||||
|
||||
|
||||
def generate_puzzle(
|
||||
n: int,
|
||||
capacity: int,
|
||||
rng: random.Random,
|
||||
attempts: int,
|
||||
) -> tuple[list[str], list[Rule], SearchResult]:
|
||||
if n < 3:
|
||||
raise ValueError("M must be at least 3 so conditional rules can be generated.")
|
||||
if capacity < 1 or capacity >= n:
|
||||
raise ValueError("Boat capacity C must be at least 1 and strictly less than M.")
|
||||
if n > 10:
|
||||
raise ValueError(
|
||||
"This exact-search version supports M up to 10. Larger values can make "
|
||||
"uniqueness checking expensive; try M <= 10."
|
||||
)
|
||||
|
||||
names = BASE_ANIMALS[:n]
|
||||
if n > len(BASE_ANIMALS):
|
||||
names += [f"animal_{i + 1}" for i in range(n - len(BASE_ANIMALS))]
|
||||
|
||||
best: tuple[list[Rule], SearchResult, float] | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
rules = random_rules(rng, n)
|
||||
result = solve(names, capacity, rules)
|
||||
|
||||
if result is None or result.ways != 1 or result.distance < n:
|
||||
continue
|
||||
|
||||
# Prefer solutions where non-final crossings move about one animal on
|
||||
# average. The final crossing is excluded because it may carry a full load.
|
||||
moves = []
|
||||
for i in range(1, len(result.path)):
|
||||
before = result.path[i - 1][0]
|
||||
after = result.path[i][0]
|
||||
moves.append((before ^ after).bit_count())
|
||||
nonfinal = moves[:-1] if len(moves) > 1 else moves
|
||||
avg = sum(nonfinal) / len(nonfinal) if nonfinal else 0.0
|
||||
score = abs(avg - 1.0)
|
||||
|
||||
if best is None or score < best[2]:
|
||||
best = (rules, result, score)
|
||||
# A perfect fit is good enough; uniqueness and minimum length already hold.
|
||||
if score == 0:
|
||||
break
|
||||
|
||||
if best is None:
|
||||
raise RuntimeError(
|
||||
f"No suitable puzzle found in {attempts} attempts. Try a different --seed, "
|
||||
"increase --attempts, or use a smaller M / boat capacity."
|
||||
)
|
||||
|
||||
rules, result, _ = best
|
||||
return names, rules, result
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate a river-crossing animal puzzle with a unique shortest solution."
|
||||
)
|
||||
parser.add_argument("M", type=int, help="total number of animals")
|
||||
parser.add_argument("C", type=int, help="maximum number of animals the boat can carry (C < M)")
|
||||
parser.add_argument("--seed", type=int, default=None, help="random seed for repeatable puzzles")
|
||||
parser.add_argument("--attempts", type=int, default=2000, help="maximum candidate puzzles to test")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.attempts < 1:
|
||||
parser.error("--attempts must be at least 1")
|
||||
|
||||
rng = random.Random(args.seed)
|
||||
try:
|
||||
names, rules, result = generate_puzzle(args.M, args.C, rng, args.attempts)
|
||||
except (ValueError, RuntimeError) as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print("=" * 68)
|
||||
print("RIVER-CROSSING PUZZLE")
|
||||
print("=" * 68)
|
||||
print(f"Animals ({len(names)}): {', '.join(names)}")
|
||||
print(f"Boat capacity: {args.C} animal(s), plus the supervisor")
|
||||
print()
|
||||
print("RULES")
|
||||
for i, rule in enumerate(rules, start=1):
|
||||
print(f"{i}. {rule.describe(names)}")
|
||||
print()
|
||||
print("PUZZLE")
|
||||
print(
|
||||
"A human supervisor must move all the animals from the left bank to the "
|
||||
"right bank. The supervisor must be in the boat for every crossing, and "
|
||||
f"the boat can carry at most {args.C} animal(s). Whenever a bank is left "
|
||||
"without the supervisor, every rule above must be satisfied. The boat may "
|
||||
"return empty. What is the safe crossing sequence?"
|
||||
)
|
||||
print()
|
||||
print("SOLUTION")
|
||||
print(f"Shortest solution: {result.distance} crossings.")
|
||||
print("Unique shortest solution: yes.")
|
||||
print("Each line below is one crossing:")
|
||||
for line in render_solution(result, names):
|
||||
print(line)
|
||||
print()
|
||||
print("Final state: all animals are on the right bank with the supervisor.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,206 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Route-first river-crossing puzzle generator (Python 3.10+, standard library).
|
||||
|
||||
Usage:
|
||||
python river_puzzle_constructive.py M C
|
||||
python river_puzzle_constructive.py 6 2 --seed 42
|
||||
python river_puzzle_constructive.py 7 3 --max-group 2
|
||||
|
||||
The script constructs a target route first, then derives animal rules that are
|
||||
compatible with that route. It does not generate random rule sets and search
|
||||
for a solution. Other solutions may exist; uniqueness is not guaranteed.
|
||||
|
||||
Rule types:
|
||||
* Travel rule: two animals from different planned boatloads may not travel
|
||||
together in the boat.
|
||||
* Safety rule: a pair may not be left together unsupervised, but only if that
|
||||
pair never occurs together on an unattended bank along the intended route.
|
||||
* Conditional safety rule: A and B may be left together only if C is present,
|
||||
but only if this condition holds at every unattended bank on the route.
|
||||
"""
|
||||
import argparse
|
||||
import random
|
||||
import sys
|
||||
from itertools import combinations
|
||||
|
||||
ANIMALS = [
|
||||
"monkey", "dog", "cat", "tortoise", "lizard", "bird", "rabbit",
|
||||
"fox", "goat", "chicken", "wolf", "duck", "snake", "hamster",
|
||||
"raccoon", "parrot", "ferret", "hedgehog", "otter", "squirrel",
|
||||
]
|
||||
|
||||
|
||||
def choose_loads(names, capacity, rng):
|
||||
"""Partition animals into loads, ensuring at least M crossings overall."""
|
||||
remaining = list(names)
|
||||
rng.shuffle(remaining)
|
||||
# With k outbound trips and k-1 returns, crossings = 2k-1 >= M.
|
||||
min_loads = (len(names) + 2) // 2
|
||||
loads = []
|
||||
while remaining:
|
||||
loads_left = min_loads - len(loads)
|
||||
if len(remaining) <= loads_left:
|
||||
size = 1
|
||||
else:
|
||||
max_size = min(capacity, len(remaining) - (loads_left - 1))
|
||||
choices = list(range(1, max_size + 1))
|
||||
size = rng.choices(choices, weights=[8] + [2] * (len(choices) - 1), k=1)[0]
|
||||
loads.append(remaining[:size])
|
||||
del remaining[:size]
|
||||
return loads
|
||||
|
||||
|
||||
def build_route(loads):
|
||||
right = frozenset()
|
||||
route = []
|
||||
for i, load in enumerate(loads):
|
||||
before = right
|
||||
right = right | frozenset(load)
|
||||
route.append({
|
||||
"direction": "left → right", "cargo": tuple(load),
|
||||
"right_before": before, "right_after": right,
|
||||
"supervisor_side_before": "left",
|
||||
})
|
||||
if i < len(loads) - 1:
|
||||
route.append({
|
||||
"direction": "right → left", "cargo": (),
|
||||
"right_before": right, "right_after": right,
|
||||
"supervisor_side_before": "right",
|
||||
})
|
||||
return route
|
||||
|
||||
|
||||
def unattended_banks(route, all_animals):
|
||||
banks = []
|
||||
for move in route:
|
||||
if move["direction"] == "left → right":
|
||||
banks.append(frozenset(all_animals - set(move["right_after"])))
|
||||
else:
|
||||
banks.append(move["right_after"])
|
||||
return banks
|
||||
|
||||
|
||||
def derive_travel_rules(loads):
|
||||
group_of = {animal: i for i, load in enumerate(loads) for animal in load}
|
||||
return [(a, b) for a, b in combinations(group_of, 2) if group_of[a] != group_of[b]]
|
||||
|
||||
|
||||
def derive_safety_rules(names, banks):
|
||||
forbidden = []
|
||||
conditional_candidates = []
|
||||
for a, b in combinations(names, 2):
|
||||
if all(not ({a, b} <= set(bank)) for bank in banks):
|
||||
forbidden.append((a, b))
|
||||
else:
|
||||
for c in names:
|
||||
if c in (a, b):
|
||||
continue
|
||||
if all(not ({a, b} <= set(bank)) or c in bank for bank in banks):
|
||||
conditional_candidates.append((a, b, c))
|
||||
return forbidden, conditional_candidates
|
||||
|
||||
|
||||
def show_set(items):
|
||||
vals = sorted(items)
|
||||
return "{" + ", ".join(vals) + "}" if vals else "∅"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("M", type=int, help="total 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("--max-group", type=int, default=None,
|
||||
help="maximum animals per outbound load (default: C)")
|
||||
parser.add_argument("--conditional-rules", type=int, default=3,
|
||||
help="maximum conditional safety rules to print")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not 3 <= args.M <= len(ANIMALS):
|
||||
parser.error(f"M must be between 3 and {len(ANIMALS)}.")
|
||||
if not 1 <= args.C < args.M:
|
||||
parser.error("C must satisfy 1 <= C < M.")
|
||||
max_group = args.C if args.max_group is None else args.max_group
|
||||
if not 1 <= max_group <= args.C:
|
||||
parser.error("--max-group must be between 1 and C.")
|
||||
if args.conditional_rules < 0:
|
||||
parser.error("--conditional-rules must be non-negative.")
|
||||
|
||||
names = ANIMALS[:args.M]
|
||||
rng = random.Random(args.seed)
|
||||
loads = choose_loads(names, max_group, rng)
|
||||
route = build_route(loads)
|
||||
banks = unattended_banks(route, set(names))
|
||||
travel_rules = derive_travel_rules(loads)
|
||||
forbidden, conditional_candidates = derive_safety_rules(names, banks)
|
||||
|
||||
# Avoid repeating the same trigger pair in the displayed conditional rules.
|
||||
rng.shuffle(conditional_candidates)
|
||||
conditional = []
|
||||
used_pairs = set()
|
||||
for a, b, c in conditional_candidates:
|
||||
key = frozenset((a, b))
|
||||
if key in used_pairs:
|
||||
continue
|
||||
conditional.append((a, b, c))
|
||||
used_pairs.add(key)
|
||||
if len(conditional) >= args.conditional_rules:
|
||||
break
|
||||
|
||||
# Validate construction invariants directly; no solution search is performed.
|
||||
assert all(1 <= len(load) <= args.C for load in loads)
|
||||
assert set(x for load in loads for x in load) == set(names)
|
||||
assert len(route) >= args.M
|
||||
for bank in banks:
|
||||
assert all(not ({a, b} <= set(bank)) for a, b in forbidden)
|
||||
assert all(not ({a, b} <= set(bank)) or c in bank for a, b, c in conditional)
|
||||
|
||||
print("=" * 70)
|
||||
print("RIVER-CROSSING PUZZLE — ROUTE-FIRST CONSTRUCTION")
|
||||
print("=" * 70)
|
||||
print(f"Animals ({args.M}): {', '.join(names)}")
|
||||
print(f"Boat capacity: {args.C} animal(s), plus the supervisor")
|
||||
print(f"Target route: {len(route)} crossings; outbound load sizes: {[len(x) for x in loads]}")
|
||||
|
||||
print("\\nTRAVEL RULES")
|
||||
if travel_rules:
|
||||
for i, (a, b) in enumerate(travel_rules, 1):
|
||||
print(f"{i}. The {a} cannot travel in the boat with the {b}.")
|
||||
else:
|
||||
print("(No travel restrictions needed for this partition.)")
|
||||
|
||||
print("\\nUNSUPERVISED-BANK SAFETY RULES")
|
||||
number = 1
|
||||
for a, b in forbidden:
|
||||
print(f"{number}. The {a} cannot be left unsupervised with the {b}.")
|
||||
number += 1
|
||||
for a, b, c in conditional:
|
||||
print(f"{number}. The {a} and the {b} can be left unsupervised together only if the {c} is present.")
|
||||
number += 1
|
||||
if not forbidden and not conditional:
|
||||
print("(No non-trivial safety rules compatible with this target route.)")
|
||||
|
||||
print("\\nPUZZLE")
|
||||
print("Move all animals from the left bank to the right bank. The supervisor must")
|
||||
print(f"accompany every crossing; the boat carries at most {args.C} animals.")
|
||||
print("The travel and unsupervised-bank rules above must always be obeyed.")
|
||||
print("The boat may return empty.")
|
||||
|
||||
print("\\nINTENDED SOLUTION")
|
||||
for i, move in enumerate(route, 1):
|
||||
cargo = ", ".join(move["cargo"]) if move["cargo"] else "empty boat"
|
||||
print(f"{i:2}. {move['direction']}: {cargo}")
|
||||
|
||||
print("\\nCONSTRUCTION NOTES")
|
||||
print("- The intended solution was constructed first; no solution search was run.")
|
||||
print("- Rules were derived directly from the intended route and checked against it.")
|
||||
print("- Every animal is transported exactly once, in a load no larger than C.")
|
||||
print(f"- The route has at least M crossings: {len(route)} >= {args.M}.")
|
||||
print("- The average outbound load is kept close to one animal.")
|
||||
print("- Uniqueness is not guaranteed; another route may satisfy the same rules.")
|
||||
print("- Travel rules and unattended-bank safety rules are separate rule types.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,247 @@
|
||||
|
||||
#!/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())
|
||||
+1082
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user