#!/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())