commit fda6b950f71990879887fb78b4dfe4026a949bdf Author: Tom Gracey Date: Sat Nov 14 01:40:39 2026 +0000 my puzzle generator (river_puzzle_tg.py) + 3 written by ChatGPT diff --git a/river_puzzle.py b/river_puzzle.py new file mode 100644 index 0000000..e129c4f --- /dev/null +++ b/river_puzzle.py @@ -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()) diff --git a/river_puzzle_constructive.py b/river_puzzle_constructive.py new file mode 100644 index 0000000..e3b41d0 --- /dev/null +++ b/river_puzzle_constructive.py @@ -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()) diff --git a/river_puzzle_guided.py b/river_puzzle_guided.py new file mode 100644 index 0000000..a3ab88e --- /dev/null +++ b/river_puzzle_guided.py @@ -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()) diff --git a/river_puzzle_tg.py b/river_puzzle_tg.py new file mode 100644 index 0000000..287c4ca --- /dev/null +++ b/river_puzzle_tg.py @@ -0,0 +1,1082 @@ +import random, sys, argparse, textwrap, pprint +from datetime import datetime + + + +class AnimalSet: + + tot_animals = 6 + + def __init__(self): + self.animal_index = 0 + self.base_animals = [ + "monkey", "dog", "cat", "tortoise", "lizard", "bird", "rabbit", + "fox", "goat", "chicken", "wolf", "duck", "snake", "hamster", + "raccoon", "parrot", "ferret", "hedgehog", "otter", "squirrel", + ] + self.animals = {} + self.animal_names = [] + self.perms = [] + self.current_perm_num = None + + for i in range(0,AnimalSet.tot_animals): + self.animals[ self.base_animals[ i ] ] = False + self.animal_names.append( self.base_animals[ i ] ) + + + def __iter__(self): + return self + + def __next__(self): + + next_animal = None + for i in range( self.animal_index, AnimalSet.tot_animals ): + animal_to_consider = self.animal_names[ i ] + if self.animals[ animal_to_consider ]: + self.animal_index = i + 1 + next_animal = animal_to_consider + break + if next_animal: + return next_animal + raise StopIteration + + def reset_index(self): + self.animal_index = 0 + + def add(self, animal): + self.animals[ animal ] = True + return self + + def add_set( self, animal_set ): + for k,v in animal_set.animals.items(): + if v: + self.add( k ) + return self + + def remove( self, animal ): + self.animals[ animal ] = False + return self + + def remove_set( self, animal_set ): + for k,v in animal_set.animals.items(): + if v: + self.remove( k ) + return self + + def add_all_animals(self): + for i in range(0,AnimalSet.tot_animals): + self.add( self.base_animals[ i ] ) + return self + + def has_animals(self): # are there any animals present? + + has_animals = False + for k,v in self.animals.items(): + if v: + has_animals = True + break + + return has_animals + + def has_animal(self, animal): # is a particular animal present? + + return self.animals[ animal ] + + + def num_animals(self): + + num_animals = 0 + for k,v in self.animals.items(): + if v: + num_animals += 1 + return num_animals + + + def pick_subset(self, num): + subset = AnimalSet() + + populated = [] + for k,v in self.animals.items(): + if v: + populated.append( k ) + + sample = random.sample( populated, num ) + + for animal in sample: + subset.add( animal ) + self.remove( animal ) + + return subset + + def inverse(self): + inverse = AnimalSet().add_all_animals() + + for k,v in self.animals.items(): + if v: + inverse.remove( k ) + + return inverse + + + def dump(self): + + if self.has_animals(): + for k,v in self.animals.items(): + if v: + print(" " + k) + print("") + else: + print(" (no animals)\n") + + def as_inline_string(self, delim = "or", prepos = "the"): + + inline = "" + animal_count = 0 + num_animals = self.num_animals() + + if num_animals == 0: + return "(no animals)" + + for k,v in self.animals.items(): + if v: + animal_count += 1 + if inline: + if animal_count == num_animals: + inline += " " + delim + " " + else: + inline += ", " + inline += prepos + " " + k + return inline + + def dump_inline( self, delim = "or", prepos = "the" ): + + inline = self.as_inline_string( delim, prepos ) + print(inline, end="") + + def clone( self ): + + cloned_set = AnimalSet() + cloned_set.add_set( self ) + return cloned_set + + def current_animal_names( self ): + + current_animal_names = [] + for k,v in self.animals.items(): + if v: + current_animal_names.append( k ) + return current_animal_names + + + def perm( self, num, include_zero = False ): + + current_animal_names = self.current_animal_names() + if self.current_perm_num == None or self.current_perm_num != num: + self.zero_perm( num ) + else: + if len(self.perms) == 0: + return None + self.inc_perm() + + perm_set = AnimalSet() + final_perm = True + for perm_i in range(0,len( self.perms )): + if self.perms[ perm_i ] < len( current_animal_names ): + animal = current_animal_names[ self.perms[ perm_i ] ] + perm_set.add( animal ) + final_perm = False + else: + self.perms.pop(perm_i) + break + if final_perm: + if include_zero: + return AnimalSet() + else: + return None + + return perm_set + + def inc_perm( self ): + + done = False + for perm_i in range(0,len( self.perms ) - 1): + animal_i = self.perms[ perm_i ] + 1 + if animal_i < self.perms[ perm_i + 1 ]: + self.perms[ perm_i ] = animal_i + done = True + break + else: + self.perms[ perm_i ] = perm_i + if not done: + self.perms[-1] += 1 + + def clear_perm( self ): + self.current_perm_num = None + + def zero_perm( self, num ): + self.current_perm_num = num + self.perms = [] + for i in range(0,num): + self.perms.append(-1) + + already = [] + current_animal_names = self.current_animal_names() + for perm_i in range(0,len( self.perms )): + for animal_i, animal_name in enumerate( current_animal_names ): + if animal_name not in already: + self.perms[ perm_i ] = animal_i + already.append( animal_name ) + break + + def is_identical( self, test_set ): + + if self.num_animals() != test_set.num_animals(): + return False + + is_identical = True + ts = test_set.clone() + ts.reset_index() + for t in ts: + if not self.has_animal( t ): + is_identical = False + break + return is_identical + + +class Step: + + def __init__(self): # The default step has all animals on the left bank, with none transported + self.left_bank_before = AnimalSet().add_all_animals() + self.right_bank_before = AnimalSet() + self.is_outgoing = True + self.transit_animals = AnimalSet() + self.unsupervised = AnimalSet().add_all_animals() + self.left_bank_after = AnimalSet().add_all_animals() + self.right_bank_after = AnimalSet() + self.already_travelled = AnimalSet() + + def dump_step(self): + + out_or_in = "Incoming" + if self.is_outgoing: + out_or_in = "Outgoing" + + print( "Transported (" + out_or_in + "): ", end="" ) + self.transit_animals.dump_inline("and") + print("") + + print( "Left Bank (at start): ", end="") + self.left_bank_before.dump_inline("and") + print("") + + print( "Right Bank (at start): ", end="") + self.right_bank_before.dump_inline("and") + print("") + + print( "Already travelled: ", end="") + self.already_travelled.dump_inline("and") + print("") + + print( "Left Bank (at end): ", end="") + self.left_bank_after.dump_inline("and") + print("") + + print( "Right Bank (at end): ", end="") + self.right_bank_after.dump_inline("and") + print("") + + def is_identical( self, test_step ): + + is_identical = True + if not ( + self.left_bank_before.is_identical( test_step.left_bank_before ) and \ + self.right_bank_before.is_identical( test_step.right_bank_before ) and \ + self.is_outgoing == test_step.is_outgoing and \ + self.transit_animals.is_identical( test_step.transit_animals ) and \ + self.unsupervised.is_identical( test_step.unsupervised ) and \ + self.left_bank_after.is_identical( test_step.left_bank_after ) and \ + self.right_bank_after.is_identical( test_step.right_bank_after ) and \ + self.already_travelled.is_indentical( test_step.already_travelled ) + ): + identical = False + + return is_identical + + + + +class StepManager: + + def __init__(self): + self.max_boat_animals = 2 + self.constraint_factor = 0.5 + self.steps = [] + self.left_bank_animals = AnimalSet() + self.left_bank_animals.add_all_animals() + self.right_bank_animals = AnimalSet() + + def add_step( self, step ): + + self.steps.append( step ) + + def prepend_step( self, step ): + + self.steps.insert(0, step) + + def dump_steps( self ): + + for i,step in enumerate(self.steps): + print(f"Step {i + 1}:\n") + step.dump_step() + print(f"------------------------") + print("\n") + + def choose_step( self, is_outgoing, num_transit_animals, already_travelled ): + + step = Step() + step.already_travelled = already_travelled + step.left_bank_before = self.left_bank_animals.clone() + step.right_bank_before = self.right_bank_animals.clone() + step.is_outgoing = is_outgoing + + transit_from = self.right_bank_animals + transit_to = self.left_bank_animals + if is_outgoing: + transit_from = self.left_bank_animals + transit_to = self.right_bank_animals + + step.transit_animals = transit_from.pick_subset( num_transit_animals ) + step.already_travelled.add_set( step.transit_animals ) + step.unsupervised = transit_from.clone() + transit_to.add_set( step.transit_animals ) + step.left_bank_after = self.left_bank_animals.clone() + step.right_bank_after = self.right_bank_animals.clone() + self.add_step( step ) + return step + + + def choose_steps( self ): + + all_transported = False + already_travelled = AnimalSet() + while True: + + outgoing_boat_animals = self.max_boat_animals + if self.left_bank_animals.num_animals() < self.max_boat_animals: + outgoing_boat_animals = self.left_bank_animals.num_animals() + + step = self.choose_step( True, outgoing_boat_animals, already_travelled ) + already_travelled = step.already_travelled.clone() + + if not self.left_bank_animals.has_animals(): + break + + step = self.choose_step( False, random.randint(0,self.max_boat_animals - 1), already_travelled ) + already_travelled = step.already_travelled.clone() + + def reduce_strictness( self, animal_set ): + + num_to_set = animal_set.num_animals() + if animal_set.num_animals() > 1: + num_to_set = int( animal_set.num_animals() * self.constraint_factor ) + if num_to_set == 0: + num_to_set = 1 + less_strict = animal_set.pick_subset( num_to_set ) + return less_strict + + def always_transported_with( self, animal ): + + always_transported_with = AnimalSet().add_all_animals().remove( animal ) + for step in self.steps: + if not step.transit_animals.has_animal( animal ): + continue + + step.transit_animals.reset_index() + all_animals_cp = AnimalSet().add_all_animals() + for animal_cp in all_animals_cp: + if not step.transit_animals.has_animal( animal_cp ): + always_transported_with.remove( animal_cp ) + return self.reduce_strictness( always_transported_with ) + + + def never_transported_with( self, animal ): + + transported_together = AnimalSet() + for step in self.steps: + if not step.transit_animals.has_animal( animal ): + continue + + step.transit_animals.reset_index() + for transit_animal in step.transit_animals: + if transit_animal == animal: + continue + transported_together.add( transit_animal ) + + never_transported_with = transported_together.inverse() + return self.reduce_strictness( never_transported_with ) + + + def always_unsupervised_with( self, animal ): + + always_unsupervised_with = AnimalSet().add_all_animals().remove( animal ) + for step in self.steps: + if not step.unsupervised.has_animal( animal ): + continue + + all_animals_cp = AnimalSet().add_all_animals() + + for animal_cp in all_animals_cp: + if not step.unsupervised.has_animal( animal_cp ): + always_unsupervised_with.remove( animal_cp ) + return self.reduce_strictness( always_unsupervised_with ) + + + def never_unsupervised_with( self, animal ): + + never_unsupervised_with = AnimalSet().add_all_animals().remove( animal ) + + for step in self.steps: + if not step.unsupervised.has_animal( animal ): + continue + + step.unsupervised.reset_index() + for unsupervised_animal in step.unsupervised: + if unsupervised_animal == animal: + continue + never_unsupervised_with.remove( unsupervised_animal ) + + return self.reduce_strictness( never_unsupervised_with ) + + def never_replaces( self, animal ): + + never_replaces = AnimalSet().add_all_animals().remove( animal ) + for i in range(0,len(self.steps)-1): + next_step = self.steps[i+1] + + if not next_step.transit_animals.has_animal( animal ): + continue + + this_step = self.steps[i] + never_replaces.remove_set( this_step.transit_animals ) + + return self.reduce_strictness( never_replaces ) + + def always_replaces( self, animal ): + + if self.steps[0].transit_animals.has_animal( animal ): # we can't always be replacing any animal + return AnimalSet() # if we travel on the first step + + always_replaces = AnimalSet().add_all_animals().remove( animal ) + for i in range(0,len(self.steps)-1): + next_step = self.steps[i+1] + + if not next_step.transit_animals.has_animal( animal ): + continue + + this_step = self.steps[i] + did_not_replace = this_step.transit_animals.inverse() + always_replaces.remove_set( did_not_replace ) + + return self.reduce_strictness( always_replaces ) + + def always_travels_after( self, animal ): + + always_travels_after = AnimalSet() + for step in self.steps: + if step.transit_animals.has_animal( animal ): + break + always_travels_after.add_set( step.transit_animals ) + + return self.reduce_strictness( always_travels_after ) + + def is_identical( self, test_sm ): + + if len(self.steps) != len(test_sm.steps): + return False + + is_identical = True + for i,test_step in enumerate(test_sm.steps): + if not self.steps[i].is_identical( test_step ): + is_identical = False + break + + return is_identical + + + + +class RuleManager: + + def __init__(self, sm): + self.solution_sm = sm + self.rules = [] + self.unsupervised_with = { "never" : {}, "always" : {} } + self.transported_with = { "never" : {}, "always" : {} } + self.replaces = {"never" : {}, "always" : {} } + self.always_travels_after = {} + self.allow_zero_on_return = True + + def set_unsupervised_with( self, type, animal, animal_set ): + self.unsupervised_with[ type ][ animal ] = animal_set + + def set_transported_with( self, type, animal, animal_set ): + self.transported_with[ type ][ animal ] = animal_set + + def set_replaces( self, type, animal, animal_set): + self.replaces[ type ][ animal ] = animal_set + + def set_always_travels_after( self, animal, animal_set ): + self.always_travels_after[ animal ] = animal_set + + def get_unsupervised_with( self, type, animal ): + unsupervised_with = self.unsupervised_with[ type ][ animal ] + return unsupervised_with + + def get_transported_with( self, type, animal ): + transported_with = self.transported_with[ type ][ animal ] + return transported_with + + def get_replaces( self, type, animal ): + replaces = self.replaces[ type ][ animal ] + return replaces + + def get_always_travels_after( self, animal ): + return self.always_travels_after[ animal ] + + def set_rules( self ): + + all_animals = AnimalSet().add_all_animals() + seen_animals = AnimalSet() + + for animal in all_animals: + + seen_animals.add( animal ) + + always_transported_with = self.solution_sm.always_transported_with( animal ) + never_transported_with = self.solution_sm.never_transported_with( animal ) + never_transported_with.remove_set( seen_animals ) + + always_unsupervised_with = self.solution_sm.always_unsupervised_with( animal ) + never_unsupervised_with = self.solution_sm.never_unsupervised_with( animal ) + + never_replaces = self.solution_sm.never_replaces( animal ) + always_replaces = self.solution_sm.always_replaces( animal ) + always_travels_after = self.solution_sm.always_travels_after( animal ) + + self.set_unsupervised_with( "never", animal, never_unsupervised_with ) + self.set_unsupervised_with( "always", animal, always_unsupervised_with ) + self.set_transported_with( "never", animal, never_transported_with ) + self.set_transported_with( "always", animal, always_transported_with ) + self.set_replaces( "never", animal, never_replaces ) + self.set_replaces( "always", animal, always_replaces ) + self.set_always_travels_after( animal, always_travels_after ) + + def gen_rule_descriptions( self ): + + all_animals = AnimalSet().add_all_animals() + for animal in all_animals: + + never_unsupervised_with = self.get_unsupervised_with( "never", animal ) + if never_unsupervised_with.has_animals(): + self.rules.append( f"The {animal} can never be left unsupervised with " + never_unsupervised_with.as_inline_string() ) + + always_unsupervised_with = self.get_unsupervised_with("always", animal ) + if always_unsupervised_with.has_animals(): + self.rules.append( f"The {animal} can only be left unsupervised if accompanied by " + always_unsupervised_with.as_inline_string("and") ) + + never_transported_with = self.get_transported_with( "never", animal ) + if never_transported_with.has_animals(): + self.rules.append(f"The {animal} can never be transported with " + never_transported_with.as_inline_string() ) + + always_transported_with = self.get_transported_with( "always", animal ) + if always_transported_with.has_animals(): + self.rules.append(f"The {animal} can only be transported if accompanied with " + always_transported_with.as_inline_string("and") ) + + never_replaces = self.get_replaces( "never", animal ) + if never_replaces.has_animals(): + self.rules.append(f"The {animal} cannot get on the boat if " + never_replaces.as_inline_string("or") + " just got off it") + + always_replaces = self.get_replaces( "always", animal ) + if always_replaces.has_animals(): + self.rules.append(f"The {animal} can only get on the boat if " + always_replaces.as_inline_string("and") + " just got off it") + + always_travels_after = self.get_always_travels_after( animal ) + if always_travels_after.has_animals(): + self.rules.append(f"The {animal}'s first trip must always be after the first trip of " + always_travels_after.as_inline_string("and")) + + def dump_rules( self ): + + for i,rule in enumerate(self.rules): + print(f"{i+1}: {rule}") + + def get_allowed_steps( self, previous_step, max_boat_animals ): + + if previous_step and previous_step.left_bank_after.num_animals() == 0: # we're done if the left + return [] # bank is empty + + left_bank_animals = AnimalSet().add_all_animals() + right_bank_animals = AnimalSet() + is_outgoing = True + if previous_step: + left_bank_animals = previous_step.left_bank_after + right_bank_animals = previous_step.right_bank_after + is_outgoing = not previous_step.is_outgoing + + from_bank_animals = right_bank_animals + if is_outgoing: + from_bank_animals = left_bank_animals + + steps = [] + + from_bank_animals.clear_perm() + + allow_zero = False + if self.allow_zero_on_return: + allow_zero = not is_outgoing + + if from_bank_animals.num_animals() < max_boat_animals: + max_boat_animals = from_bank_animals.num_animals() + + while transit_animals := from_bank_animals.perm( max_boat_animals, allow_zero ): + + if previous_step and transit_animals.is_identical( previous_step.transit_animals ): + continue + + unsupervised_animals = from_bank_animals.clone().remove_set( transit_animals ) + + allowed = self.can_be_unsupervised( unsupervised_animals ) + if allowed: + allowed = self.can_travel_together( transit_animals ) + if allowed and previous_step: + allowed = self.can_replace( previous_step, transit_animals ) + if allowed: + allowed = self.free_to_travel_now( previous_step, transit_animals ) + + if allowed: + step = Step() + step.left_bank_before = left_bank_animals.clone() + step.right_bank_before = right_bank_animals.clone() + step.is_outgoing = is_outgoing + step.transit_animals = transit_animals + + step.already_travelled = AnimalSet().add_set( step.transit_animals ) + if previous_step: + step.already_travelled = previous_step.already_travelled.clone().add_set( step.transit_animals ) + if is_outgoing: + step.left_bank_after = left_bank_animals.clone().remove_set(transit_animals) + step.right_bank_after = right_bank_animals.clone().add_set(transit_animals) + else: + step.left_bank_after = left_bank_animals.clone().add_set( transit_animals ) + step.right_bank_after = right_bank_animals.clone().remove_set( transit_animals ) + + steps.append( step ) + + return steps + + def can_travel_together( self, animals ): + + ok = self.check_never_ok( "transported", animals ) + if ok: + ok = self.check_always_ok( "transported", animals ) + return ok + + def can_replace( self, previous_step, transit_animals ): + + allowed = self.check_never_replace( previous_step, transit_animals ) + if allowed: + allowed = self.check_always_replace( previous_step, transit_animals ) + return allowed + + def check_never_replace( self, previous_step, transit_animals ): + + if not previous_step: + return True + + can_replace = True + transit_animals.reset_index() + for transit_animal in transit_animals: + never_replaces = self.get_replaces( "never", transit_animal ) + + previous_step.transit_animals.reset_index() + for previous_animal in previous_step.transit_animals: + + if never_replaces.has_animal( previous_animal ): + can_replace = False + break + if not can_replace: + break + return can_replace + + def check_always_replace( self, previous_step, transit_animals ): + + can_replace = True + transit_animals.reset_index() + for transit_animal in transit_animals: + always_replaces = self.get_replaces( "always", transit_animal ) + if not always_replaces.has_animals(): + continue + if not previous_step: + can_replace = False + break + + previous_step.transit_animals.reset_index() + for previous_animal in previous_step.transit_animals: + if not always_replaces.has_animal( previous_animal ): + can_replace = False + break + if not can_replace: + break + return can_replace + + def free_to_travel_now( self, previous_step, transit_animals ): + + already_travelled = AnimalSet() + if previous_step: + already_travelled = previous_step.already_travelled + + free_to_travel = True + + transit_animals.reset_index() + for transit_animal in transit_animals: + if already_travelled.has_animal( transit_animal ): + continue + + always_travels_after = self.get_always_travels_after( transit_animal ) + always_travels_after.reset_index() + for always_animal in always_travels_after: + if not already_travelled.has_animal( always_animal ): + free_to_travel = False + break + if not free_to_travel: + break + return free_to_travel + + def can_be_unsupervised( self, animals ): + + ok = self.check_never_ok( "unsupervised", animals ) + if ok: + ok = self.check_always_ok( "unsupervised", animals ) + return ok + + def check_never_ok( self, type, animals ): + + never_ok = True + animals.reset_index() + for animal in animals: + method = "get_" + type + "_with" + never_set = getattr(self,method)("never", animal) + + never_set.reset_index() + for never_animal in never_set: + if animals.has_animal( never_animal ): + never_ok = False + break + if not never_ok: + break + return never_ok + + def check_always_ok( self, type, animals ): + + always_ok = True + animals.reset_index() + for animal in animals: + method = "get_" + type + "_with" + always_set = getattr(self, method)("always", animal ) + always_set.reset_index() + for always_animal in always_set: + if not animals.has_animal( always_animal ): + always_ok = False + break + if not always_ok: + break + return always_ok + + def find_paths( self ): + + print(f"Finding paths") + sms = self.find_remaining_steps( None ) + return sms + + + def find_remaining_steps( self, previous_step): # Not efficient - needs a better algorithm + + max_animals = self.solution_sm.max_boat_animals + + if previous_step and previous_step.is_outgoing: + max_animals = previous_step.transit_animals.num_animals() - 1 + + allowed_steps = self.get_allowed_steps( previous_step, max_animals ) + + all_sms = [] + for allowed_step in allowed_steps: + + if allowed_step.left_bank_after.num_animals() == 0: + sm = StepManager() + sm.add_step( allowed_step ) + all_sms.append( sm ) + + else: + sms = self.find_remaining_steps( allowed_step) + + if len(sms) == 0: + sm = StepManager() + sm.add_step( allowed_step ) + all_sms.append( sm ) + else: + for sm in sms: + sm.prepend_step( allowed_step ) + all_sms.append( sm ) + + return all_sms + + def is_simple_unique( self ): + + previous_step = None + is_unique = True + + max_i = 0 + for i,step in enumerate( self.solution_sm.steps ): + + allowed_steps = self.get_allowed_steps( previous_step, self.solution_sm.max_boat_animals ) + + if len( allowed_steps ) != 1: + is_unique = False + break + previous_step = allowed_steps[0] + return is_unique + + def is_varied_incoming( self ): + + seen = [] + + target = 2 + + if self.solution_sm.max_boat_animals > 2: + target = int( 1 + self.solution_sm.max_boat_animals / 2 ) + + is_varied_incoming = False + for step in self.solution_sm.steps: + + na = step.transit_animals.num_animals() + + if not na in seen: + seen.append( na ) + if len(seen) >= target: + is_varied_incoming = True + break + return is_varied_incoming + + + +class PuzzleManager: + + def __init__(self): + self.max_boat_animals = 2 + self.constraint_factor = 0.5 + self.max_retries = 5000 + self.sm = None + self.rm = None + self.paths_sms = [] + self.solution_sms = [] + self.min_solution_sms = [] + + def init_puzzle(self, verbose = False): + + self.sm = StepManager() + self.sm.constraint_factor = self.constraint_factor + + self.choose_solution( verbose ) + self.rm = RuleManager( self.sm ) + self.gen_rules( verbose ) + + def choose_solution(self, verbose = False): + + self.sm.max_boat_animals = self.max_boat_animals + + self.sm.choose_steps() + + if verbose: + print(f"=> Decided 1 solution to start with") + + def gen_rules(self, verbose = False): + + self.rm.set_rules() + self.rm.gen_rule_descriptions() + + if verbose: + print(f"=> Set rules based on the originally chosen solution") + + def find_simple_unique_puzzle(self): + + unique_found = False + for i in range(0,self.max_retries): + self.sm = StepManager() + self.sm.constraint_factor = 1 + self.choose_solution() + self.rm = RuleManager( self.sm ) + self.gen_rules() + if self.rm.is_simple_unique(): + print("=> Found a simple unique puzzle!") + unique_found = True + break + if not unique_found: + print(f"=> Failed to find a unique puzzle in {self.max_simple_unique_tries} attempts") + + def find_varied_incoming_puzzle(self): + + varied_incoming_found = False + for i in range(0, self.max_retries): + self.init_puzzle( True ) + if self.rm.is_varied_incoming(): + varied_incoming_found = True + break + + if not varied_incoming_found: + print(f"=> Failed to find a unique puzzle in {self.max_simple_unique_tries} attempts") + + + def clear_report( self ): + self.report = "" + + def add_to_report( self, text ): + self.report += "=> " + text + "\n" + + def dump_report( self ): + print(self.report) + + def find_min_solutions(self): + + self.clear_report() + self.add_to_report("Finding available paths based on the rules") + + self.paths_sms = self.rm.find_paths() + self.add_to_report(f"Found {len(self.paths_sms)} paths!") + + num_solutions = 0 + min_step_solution_sm = None + min_steps = 0 + self.solution_sms = [] + for i,paths_sm in enumerate(self.paths_sms): # find minimum number of steps made amongst solutions + if not paths_sm.steps[-1].left_bank_after.has_animals(): + num_solutions +=1 + self.solution_sms.append( paths_sm ) + if not min_steps or len(paths_sm.steps) < min_steps: + min_steps = len(paths_sm.steps) + self.add_to_report(f"Of which {num_solutions} were solutions") + + # gather all min step solutions + num_min_step_solutions = 1 + self.min_solution_sms = [] + solution_content_str = "" + if min_steps == 0 or len(self.sm.steps) < min_steps: + self.min_solution_sms = [ self.sm ] # there's only one if the original is the shortest + self.add_to_report("This was the only solution found with the minimum number of steps.") + min_steps = len(self.sm.steps) + else: + num_min_step_solutions = 0 + if len(self.sm.steps) == min_steps: # if original is the same length as the others found... + is_identical = False + for solution_sm in self.solution_sms: # .. check if its the same... + if solution_sm.is_identical( self.sm ): + is_identical = True + break + if is_identical: + self.add_to_report("The original was the same as one of those found.") + else: + self.min_solution_sms.append( sm ) # ... and add it to the set if not + self.add_to_report("The original solution was different to those found, and has been added to the list.") + num_solutions += 1 + + for solution_sm in self.solution_sms: + if len(solution_sm.steps) == min_steps: + self.min_solution_sms.append( solution_sm ) + num_min_step_solutions += 1 + + self.add_to_report(f"{num_solutions} solutions were found among checked paths") + self.add_to_report(f"In total {num_min_step_solutions} solutions were solved in a minimum number of steps ({min_steps} steps)") + self.add_to_report(f"The original chosen solution has {len(self.sm.steps)} steps") + + def dump_puzzle(self): + + print("\n== RIVER CROSSING PUZZLE ==\n") + + animals = AnimalSet().add_all_animals().as_inline_string("and", "a") + + puzzle_text = textwrap.fill(f"""You are a human on the side of river with {animals}. You are responsible for looking after these animals. You need to get the animals to the other side of the river using a boat which is moored at the side of the river. However, you need to be aboard the boat to steer it, and the boat can only carry {self.max_boat_animals} animals in addition to yourself. The animals won't run away if left alone, but they might attack or eat each other in certain circumstances, which cannot be allowed. The rules are as follows:""", width = 100) + + print(puzzle_text) + + print("\n========= RULES ===========\n") + self.rm.dump_rules() + + def dump_min_solutions( self ): + + print("\n\n=== MIN STEP SOLUTIONS ===\n") + for i,min_sm in enumerate(self.min_solution_sms): + print(f"--- Solution {i+1} ---\n") + min_sm.dump_steps() + + def dump_original_solution( self ): + + print("\n\n=== ORIGINAL SOLUTION ====\n") + self.sm.dump_steps() + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser( + prog = "river-crossing-tg", + description="River Crossing Puzzle Generator - TG Oct 2026 - Written entirely by a human!" + ) + + parser.add_argument("-a", "--max-animals", type=int, default=6, help="The number of animals to transport") + parser.add_argument("-b", "--boat-capacity", type=int, default=2, help="The maximum number of animals that can be transported in the boat at one time") + parser.add_argument("-B", "--buster", action="store_true", default=False, help="Create a ChatGPT \"busting\" puzzle (one ChatGPT is likely to struggle with). Note this assumes a set of parameters, and will override them if they are set independently") + parser.add_argument("-c", "--constraint-factor", type=float, default=0.5, help="The strictness of the rules to apply. 1 = strict as possible (can lead to a forced puzzle), 0 = least strict (puzzle may have many solutions)") + parser.add_argument("-m", "--min-solutions", action="store_true", default=False, help="Also check for shorter solutions (than the original assumed solution) which obey the same rule set. Note this is a search-type operation which may take a very long time (and consume system resources) for higher complexity puzzles, and probably should not be used in this case.") + parser.add_argument("-u", "--simple-unique", action="store_true", default=False, help="Create a \"simple unique\" puzzle - where there is always only one possible next move until all animals are transported. This overrides the \"constraint factor\" setting it to 1. Potentially useful for testing. Otherwise, not very challenging.") + parser.add_argument("-r", "--max-retries", type=int, default=5000, help="Applies when search-type operations are involved. This is the hard upper limit to the number of possible retries, above which the job is aborted") + parser.add_argument("-s", "--seed", type=int, default=None, help="The random seed to use. Stating an explicit seed is helpful for repeat generations of the same puzzle. If not specified, the seed is taken from the clock") + + + args = parser.parse_args() + + if args.seed: + random.seed(args.seed) + else: + random.seed(random.seed(datetime.now().timestamp())) + + pm = PuzzleManager() + + # Set params from command line + pm.max_boat_animals = args.boat_capacity + AnimalSet.tot_animals = args.max_animals + pm.max_retries = args.max_retries + pm.constraint_factor = args.constraint_factor + find_min_solutions = args.min_solutions + + if args.buster: + + # Override with "busting" parameters. What should these be though? + pm.max_boat_animals = 3 + AnimalSet.tot_animals = 12 + pm.constraint_factor = 0.8 + find_min_solutions = False + + pm.find_varied_incoming_puzzle() + + elif args.simple_unique: + + pm.find_simple_unique_puzzle() + + else: + + pm.init_puzzle(True) + + pm.dump_puzzle() + pm.dump_original_solution() + + if find_min_solutions: + pm.find_min_solutions() + pm.dump_report() + pm.dump_min_solutions()