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())
|
||||
Reference in New Issue
Block a user