# SPDX-License-Identifier: BSD-3-Clause """Procedural problem generators for the eight CrossDomain task families. Every generator takes a ``random.Random`` and returns a :class:`Problem` whose reference answer is computed by the generator itself, so every problem is exactly verifiable and the supply of problems is unlimited. """ from __future__ import annotations import base64 import codecs import datetime as dt import hashlib import heapq import ipaddress import itertools import json import math import random import re import string from dataclasses import dataclass from fractions import Fraction from typing import Callable @dataclass class Problem: prompt: str answer: str kind: str = "num" # num | int | text | text_cs | list abs_tol: float = 0.0 rel_tol: float = 1e-3 # --------------------------------------------------------------------------- # # Grading # --------------------------------------------------------------------------- # _NUM_RE = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") def _parse_number(text: str) -> float | None: t = text.strip().replace("−", "-") t = re.sub(r"(?<=\d),(?=\d{3}\b)", "", t) t = t.replace("$", "").replace("%", "") frac = re.search(r"(? str: t = text.strip().strip("`'\"").strip() t = re.sub(r"\s+", " ", t).rstrip(".") return t if case_sensitive else t.lower() def grade(problem: Problem, submitted: str) -> bool: if problem.kind in ("num", "int"): got = _parse_number(submitted) if got is None or not math.isfinite(got): return False want = float(problem.answer) if problem.kind == "int": return abs(got - want) < 1e-9 return abs(got - want) <= max(problem.abs_tol, problem.rel_tol * abs(want)) if problem.kind == "list": got = [_norm_text(x) for x in submitted.split(",") if x.strip()] want = [_norm_text(x) for x in problem.answer.split(",")] return got == want if problem.kind == "text_cs": return _norm_text(submitted, True) == _norm_text(problem.answer, True) return _norm_text(submitted) == _norm_text(problem.answer) def _fmt(x: float, nd: int = 2) -> str: return f"{x:.{nd}f}" # --------------------------------------------------------------------------- # # Software engineering # --------------------------------------------------------------------------- # _PKG = ["auth", "cache", "cli", "core", "db", "http", "log", "metrics", "orm", "parser", "queue", "router", "schema", "storage", "utils", "web", "worker", "config"] def se_topo_order(rng: random.Random) -> Problem: names = rng.sample(_PKG, rng.randint(6, 9)) order = names[:] rng.shuffle(order) deps = {n: set() for n in names} for i, n in enumerate(order): for m in order[:i]: if rng.random() < 0.3: deps[n].add(m) lines = [f"- {n}: depends on {', '.join(sorted(deps[n])) or '(nothing)'}" for n in sorted(names)] indeg = {n: len(deps[n]) for n in names} users = {n: [m for m in names if n in deps[m]] for n in names} heap = [n for n in names if indeg[n] == 0] heapq.heapify(heap) out = [] while heap: n = heapq.heappop(heap) out.append(n) for m in users[n]: indeg[m] -= 1 if indeg[m] == 0: heapq.heappush(heap, m) prompt = ( "A build tool installs packages one at a time. A package may only be installed after all " "of its dependencies. Whenever several packages are ready, it installs the alphabetically " "first one.\n" + "\n".join(lines) + "\nGive the full install order as a comma-separated list of package names." ) return Problem(prompt, ", ".join(out), kind="list") def _ver_key(v: str) -> tuple[int, ...]: return tuple(int(p) for p in v.split(".")) def se_semver(rng: random.Random) -> Problem: vs = set() while len(vs) < rng.randint(8, 12): vs.add(f"{rng.randint(1, 3)}.{rng.randint(0, 6)}.{rng.randint(0, 12)}") versions = sorted(vs, key=_ver_key) base = rng.choice(versions) X, Y, Z = _ver_key(base) op = rng.choice(["^", "~", "range"]) if op == "^": cons, lo, hi = f"^{base}", (X, Y, Z), (X + 1, 0, 0) elif op == "~": cons, lo, hi = f"~{base}", (X, Y, Z), (X, Y + 1, 0) else: hi_v = (X, Y + rng.randint(1, 3), 0) cons, lo, hi = f">={base} <{'.'.join(map(str, hi_v))}", (X, Y, Z), hi_v ok = [v for v in versions if lo <= _ver_key(v) < hi] shown = versions[:] rng.shuffle(shown) prompt = ( f"A registry has these versions of a library: {', '.join(shown)}.\n" f"Using npm semantic-versioning rules, which is the highest version that satisfies " f"the constraint `{cons}`? Answer with the version string only." ) return Problem(prompt, max(ok, key=_ver_key), kind="text") def se_rle(rng: random.Random) -> Problem: alphabet = rng.choice(["ab", "abc", "xyz", "ABab"]) runs = [] for _ in range(rng.randint(5, 9)): c = rng.choice(alphabet) if runs and runs[-1][0] == c: continue runs.append((c, rng.randint(1, 12))) s = "".join(c * k for c, k in runs) enc = "".join(f"{k}{c}" for c, k in runs) if rng.random() < 0.5: prompt = ( "Run-length encode the string below: replace each maximal run of a repeated character " "with its length followed by the character (length is always written, even when 1). " f"Characters are case-sensitive.\nString: {s}\nAnswer with the encoded string only." ) return Problem(prompt, enc, kind="text_cs") prompt = ( "The string below is run-length encoded: each group is a decimal count followed by one " f"character. Decode it and report how many characters the decoded string has, and how " f"many of them are '{runs[0][0]}'. Answer as two integers separated by a comma " f"(total, count).\nEncoded: {enc}" ) total = sum(k for _, k in runs) cnt = sum(k for c, k in runs if c == runs[0][0]) return Problem(prompt, f"{total}, {cnt}", kind="list") def se_json_query(rng: random.Random) -> Problem: statuses = ["shipped", "pending", "cancelled", "delivered"] orders = [] for i in range(rng.randint(5, 8)): items = [ {"sku": f"SKU-{rng.randint(100, 999)}", "qty": rng.randint(1, 5), "price": round(rng.uniform(2, 80), 2)} for _ in range(rng.randint(1, 4)) ] orders.append({"id": 1000 + i, "status": rng.choice(statuses), "items": items}) want = rng.choice(statuses[:2] + [statuses[3]]) min_qty = rng.randint(1, 3) total = sum(it["qty"] * it["price"] for o in orders if o["status"] == want for it in o["items"] if it["qty"] >= min_qty) prompt = ( "Here is an API response:\n" + json.dumps({"orders": orders}, separators=(",", ":")) + f"\nCompute the sum of qty*price over all line items with qty >= {min_qty} that belong to " f"orders whose status is \"{want}\". Answer with a number rounded to 2 decimals." ) return Problem(prompt, _fmt(total), abs_tol=0.011, rel_tol=0) def se_regex_count(rng: random.Random) -> Problem: patterns = [ (r"^[a-z]+_[a-z]+$", "snake_case identifiers made of two lowercase words"), (r"^v\d+\.\d+\.\d+$", "version tags like v1.2.3"), (r"^[A-Z][a-zA-Z]*Error$", "class names ending in Error"), (r"^\d{4}-\d{2}-\d{2}$", "ISO dates"), ] pat, _ = rng.choice(patterns) pool = ["user_id", "UserId", "v1.2.3", "v10.0.12", "1.2.3", "v1.2", "ValueError", "valueError", "KeyError", "Error", "2024-01-05", "2024-1-05", "20240105", "max_len", "max__len", "_private", "TypeErrors", "v0.0.0", "IOError", "1999-12-31", "a_b", "snake_case_x"] items = rng.sample(pool, rng.randint(9, 14)) n = sum(1 for x in items if re.search(pat, x)) prompt = ( f"How many of the following strings fully match the Python regular expression " f"`{pat}` (using re.search)?\n" + "\n".join(items) + "\nAnswer with an integer." ) return Problem(prompt, str(n), kind="int") # --------------------------------------------------------------------------- # # Industrial and physical systems # --------------------------------------------------------------------------- # def ind_oee(rng: random.Random) -> Problem: planned = rng.choice([420, 450, 480]) down = rng.randint(20, 90) ict = rng.choice([0.5, 0.75, 1.0, 1.2, 1.5]) # minutes per unit run = planned - down total = int(run / ict * rng.uniform(0.7, 0.97)) defects = rng.randint(0, total // 10) a, p, q = run / planned, ict * total / run, (total - defects) / total prompt = ( f"A machine has {planned} min of planned production time in a shift and {down} min of " f"unplanned downtime. Ideal cycle time is {ict} min/unit. It produced {total} units, of " f"which {defects} were defective. Compute OEE (availability x performance x quality) as a " f"percentage rounded to 1 decimal." ) return Problem(prompt, _fmt(100 * a * p * q, 1), abs_tol=0.1, rel_tol=0) def ind_tank(rng: random.Random) -> Problem: cap = rng.choice([2000, 5000, 8000, 12000]) level = rng.randint(5, 60) / 100 qin = rng.randint(40, 200) qout = rng.randint(10, qin - 10) t = cap * (1 - level) / (qin - qout) prompt = ( f"A {cap} L tank is {int(level * 100)}% full. Water enters at {qin} L/min and is drawn off " f"at {qout} L/min at the same time. How many minutes until the tank is full? Round to 2 decimals." ) return Problem(prompt, _fmt(t), abs_tol=0.01) def ind_circuit(rng: random.Random) -> Problem: v = rng.choice([5, 9, 12, 24, 48]) r1, r2, r3 = (rng.choice([10, 22, 47, 68, 100, 150, 220, 330, 470]) for _ in range(3)) rp = r2 * r3 / (r2 + r3) i = v / (r1 + rp) i3 = i * rp / r3 prompt = ( f"A {v} V ideal source drives R1 = {r1} ohm in series with the parallel pair " f"R2 = {r2} ohm and R3 = {r3} ohm. What current flows through R3, in milliamps? " f"Round to 2 decimals." ) return Problem(prompt, _fmt(i3 * 1000), abs_tol=0.01) def ind_johnson(rng: random.Random) -> Problem: n = rng.randint(4, 6) jobs = {chr(65 + k): (rng.randint(1, 12), rng.randint(1, 12)) for k in range(n)} def makespan(seq): t1 = t2 = 0 for j in seq: a, b = jobs[j] t1 += a t2 = max(t2, t1) + b return t2 best = min(makespan(p) for p in itertools.permutations(jobs)) rows = "\n".join(f"- job {j}: {a} h on M1, then {b} h on M2" for j, (a, b) in jobs.items()) prompt = ( "Each job must be processed on machine M1 and then on machine M2; each machine handles one " "job at a time and jobs pass through both machines in the same order.\n" + rows + "\nWhat is the minimum possible makespan in hours? Answer with an integer." ) return Problem(prompt, str(best), kind="int") def ind_eoq(rng: random.Random) -> Problem: d = rng.choice([1200, 2400, 5000, 9600, 15000]) s = rng.choice([25, 40, 75, 120]) h = rng.choice([0.8, 1.5, 2.0, 3.5, 6.0]) q = math.sqrt(2 * d * s / h) prompt = ( f"Annual demand is {d} units, each order costs ${s} to place, and holding one unit for a " f"year costs ${h}. What is the economic order quantity? Round to the nearest whole unit." ) return Problem(prompt, str(round(q)), abs_tol=1.0, rel_tol=0) def ind_bottleneck(rng: random.Random) -> Problem: st = [(f"S{k+1}", rng.choice([30, 45, 60, 75, 90, 120]), rng.randint(1, 3)) for k in range(rng.randint(3, 5))] rate = min(m * 3600 / ct for _, ct, m in st) rows = "\n".join(f"- {n}: cycle time {ct} s per unit, {m} identical machine(s) in parallel" for n, ct, m in st) prompt = ( "A serial production line has these stations (every unit visits each station once):\n" + rows + "\nWhat is the maximum steady-state throughput of the line in units per hour? Round to 1 decimal." ) return Problem(prompt, _fmt(rate, 1), abs_tol=0.1) # --------------------------------------------------------------------------- # # Natural science # --------------------------------------------------------------------------- # def sci_halflife(rng: random.Random) -> Problem: iso, th, unit = rng.choice([("I-131", 8.02, "days"), ("Co-60", 5.27, "years"), ("C-14", 5730, "years"), ("Tc-99m", 6.01, "hours")]) m0 = rng.choice([10, 25, 50, 80, 200]) t = round(th * rng.uniform(0.3, 4.5), 1) m = m0 * 0.5 ** (t / th) prompt = ( f"{iso} has a half-life of {th} {unit}. A sample starts with {m0} mg. How many mg remain " f"after {t} {unit}? Round to 3 significant figures." ) return Problem(prompt, f"{m:.6g}", rel_tol=0.005) def sci_projectile(rng: random.Random) -> Problem: v = rng.randint(10, 60) ang = rng.choice([15, 20, 30, 37, 45, 53, 60, 70]) g = 9.81 if rng.random() < 0.5: r = v * v * math.sin(math.radians(2 * ang)) / g q = "horizontal range in metres" else: r = (v * math.sin(math.radians(ang))) ** 2 / (2 * g) q = "maximum height in metres" prompt = ( f"A projectile is launched from level ground at {v} m/s, {ang} degrees above horizontal. " f"Ignore air resistance and use g = 9.81 m/s^2. What is its {q}? Round to 2 decimals." ) return Problem(prompt, _fmt(r), abs_tol=0.01, rel_tol=0.002) def sci_gas(rng: random.Random) -> Problem: n = round(rng.uniform(0.2, 5), 2) t_c = rng.randint(-20, 150) v = round(rng.uniform(2, 50), 1) p = n * 8.314 * (t_c + 273.15) / (v / 1000) / 1000 prompt = ( f"{n} mol of an ideal gas occupies {v} L at {t_c} degrees C. Using R = 8.314 J/(mol K) and " f"T(K) = T(C) + 273.15, what is its pressure in kPa? Round to 1 decimal." ) return Problem(prompt, _fmt(p, 1), abs_tol=0.1, rel_tol=0.001) _RXNS = [ ("2 H2 + O2 -> 2 H2O", ("H2", 2, 2.016), ("O2", 1, 31.998), ("H2O", 2, 18.015)), ("N2 + 3 H2 -> 2 NH3", ("N2", 1, 28.014), ("H2", 3, 2.016), ("NH3", 2, 17.031)), ("CH4 + 2 O2 -> CO2 + 2 H2O", ("CH4", 1, 16.043), ("O2", 2, 31.998), ("CO2", 1, 44.009)), ("2 Al + 3 Cl2 -> 2 AlCl3", ("Al", 2, 26.982), ("Cl2", 3, 70.906), ("AlCl3", 2, 133.341)), ("4 Fe + 3 O2 -> 2 Fe2O3", ("Fe", 4, 55.845), ("O2", 3, 31.998), ("Fe2O3", 2, 159.687)), ] def sci_stoich(rng: random.Random) -> Problem: eq, (a, ca, ma), (b, cb, mb), (p, cp, mp) = rng.choice(_RXNS) ga = round(rng.uniform(5, 120), 1) gb = round(rng.uniform(5, 120), 1) ext = min(ga / ma / ca, gb / mb / cb) gp = ext * cp * mp prompt = ( f"Reaction: {eq}. Molar masses (g/mol): {a} {ma}, {b} {mb}, {p} {mp}. You react {ga} g of " f"{a} with {gb} g of {b}. What is the theoretical yield of {p} in grams? Round to 2 decimals." ) return Problem(prompt, _fmt(gp), abs_tol=0.01, rel_tol=0.002) def sci_genetics(rng: random.Random) -> Problem: genes = ["A", "B", "C"][: rng.randint(2, 3)] def geno(): return "".join(rng.choice([g + g, g + g.lower(), g.lower() + g.lower()]) for g in genes) p1, p2 = geno(), geno() target = {g: rng.choice(["dominant", "recessive"]) for g in genes} prob = Fraction(1) for k, g in enumerate(genes): a1, a2 = p1[2 * k: 2 * k + 2], p2[2 * k: 2 * k + 2] rec = Fraction(sum(1 for x in a1 for y in a2 if x.islower() and y.islower()), 4) prob *= rec if target[g] == "recessive" else 1 - rec desc = ", ".join(f"{target[g]} for trait {g}" for g in genes) prompt = ( f"Genes {', '.join(genes)} assort independently with complete dominance (uppercase allele " f"dominant). Cross {p1} x {p2}. What is the probability that an offspring shows the " f"phenotype: {desc}? Answer as a reduced fraction like 3/16 (or 0)." ) return Problem(prompt, str(float(prob)), rel_tol=1e-6, abs_tol=1e-9) def sci_dilution(rng: random.Random) -> Problem: c1 = rng.choice([1.0, 2.0, 5.0, 6.0, 10.0, 12.0]) c2 = round(c1 * rng.uniform(0.02, 0.6), 3) v2 = rng.choice([100, 250, 500, 1000]) v1 = c2 * v2 / c1 prompt = ( f"How many mL of a {c1} M stock solution are needed to make {v2} mL of a {c2} M solution? " f"Round to 2 decimals." ) return Problem(prompt, _fmt(v1), abs_tol=0.01) # --------------------------------------------------------------------------- # # Office and white-collar work # --------------------------------------------------------------------------- # def off_business_days(rng: random.Random) -> Problem: start = dt.date(2025, 1, 1) + dt.timedelta(days=rng.randint(0, 600)) end = start + dt.timedelta(days=rng.randint(10, 75)) span = [start + dt.timedelta(days=k) for k in range((end - start).days + 1)] weekdays = [d for d in span if d.weekday() < 5] hols = sorted(rng.sample(span, rng.randint(1, 3))) n = sum(1 for d in weekdays if d not in hols) prompt = ( f"Count the business days from {start.isoformat()} to {end.isoformat()}, both inclusive. " f"Business days are Monday-Friday, excluding these company holidays: " f"{', '.join(h.isoformat() for h in hols)}. Answer with an integer." ) return Problem(prompt, str(n), kind="int") def _hm(m: int) -> str: return f"{m // 60:02d}:{m % 60:02d}" def off_meeting(rng: random.Random) -> Problem: for attempt in range(200): people = {} for name in rng.sample(["Ana", "Ben", "Chen", "Dara", "Eli", "Fatima"], 3): busy = [] for _ in range(rng.randint(2, 4)): s = rng.randrange(9 * 60, 17 * 60 - 30, 15) busy.append((s, min(17 * 60, s + rng.choice([30, 45, 60, 90])))) people[name] = sorted(busy) dur = rng.choice([30, 45, 60]) free = None for s in range(9 * 60, 17 * 60 - dur + 1, 15): if all(not (s < e and b < s + dur) for bl in people.values() for b, e in bl): free = s break if free is not None and (free > 9 * 60 or attempt > 100): break rows = "\n".join(f"- {p}: " + ", ".join(f"{_hm(b)}-{_hm(e)}" for b, e in bl) for p, bl in people.items()) prompt = ( "Working hours are 09:00-17:00. Busy times (start inclusive, end exclusive):\n" + rows + f"\nMeetings may only start on a quarter hour. What is the earliest start time for a " f"{dur}-minute meeting with all three people? Answer as HH:MM." ) return Problem(prompt, _hm(free), kind="text") def off_pivot(rng: random.Random) -> Problem: regions = ["North", "South", "East", "West"] months = ["Jan", "Feb", "Mar"] rows = [] for _ in range(rng.randint(10, 16)): rows.append((rng.choice(regions), rng.choice(months), rng.choice(["Kim", "Lee", "Ola", "Raj"]), rng.randint(1, 40), round(rng.uniform(5, 150), 2))) r, m = rows[0][0], rows[0][1] total = sum(u * p for rr, mm, _, u, p in rows if rr == r and mm == m) csv = "region,month,rep,units,unit_price\n" + "\n".join(",".join(map(str, x)) for x in rows) prompt = ( f"{csv}\nFrom this CSV, what is the total revenue (units x unit_price) for region {r} in " f"{m}? Round to 2 decimals." ) return Problem(prompt, _fmt(total), abs_tol=0.011, rel_tol=0) def off_expenses(rng: random.Random) -> Problem: meal_cap = rng.choice([40, 50, 60]) hotel_cap = rng.choice([150, 180, 220]) cats = ["meal", "hotel", "taxi", "alcohol", "meal", "taxi"] items = [(rng.choice(cats), round(rng.uniform(8, 300), 2)) for _ in range(rng.randint(5, 9))] total = 0.0 for c, a in items: if c == "meal": total += min(a, meal_cap) elif c == "hotel": total += min(a, hotel_cap) elif c == "taxi": total += a rows = "\n".join(f"- {c}: ${a:.2f}" for c, a in items) prompt = ( f"Travel policy: each meal is reimbursed up to ${meal_cap}; each hotel night up to " f"${hotel_cap}; taxis in full; alcohol is not reimbursable. Receipts:\n{rows}\n" f"What is the total reimbursable amount? Round to 2 decimals." ) return Problem(prompt, _fmt(total), abs_tol=0.011, rel_tol=0) def off_dedupe(rng: random.Random) -> Problem: first = ["anna", "bo", "carla", "dev", "emil", "femi", "gus", "hana"] domains = ["acme.com", "globex.io", "initech.org"] base = [f"{rng.choice(first)}.{rng.choice(first)}@{rng.choice(domains)}" for _ in range(rng.randint(5, 8))] uniq = len(set(base)) out = [] for e in base: for _ in range(rng.randint(1, 3)): v = e if rng.random() < 0.5: v = v.upper() if rng.random() < 0.3 else v.capitalize() if rng.random() < 0.4: v = " " + v + " " out.append(v) rng.shuffle(out) prompt = ( "A mailing list export contains these addresses (one per line, quotes show exact text):\n" + "\n".join(f'"{x}"' for x in out) + "\nEmail addresses are case-insensitive and surrounding whitespace is noise. How many " "distinct addresses are there? Answer with an integer." ) return Problem(prompt, str(uniq), kind="int") # --------------------------------------------------------------------------- # # Finance and economics # --------------------------------------------------------------------------- # def fin_loan(rng: random.Random) -> Problem: p = rng.choice([15000, 25000, 180000, 250000, 400000]) r = rng.choice([3.5, 4.25, 5.0, 6.75, 7.9]) n = rng.choice([3, 5, 15, 30]) i = r / 100 / 12 pay = p * i / (1 - (1 + i) ** (-12 * n)) prompt = ( f"A ${p:,} loan has a {r}% annual interest rate compounded monthly and is repaid in equal " f"monthly payments over {n} years. What is the monthly payment? Round to 2 decimals." ) return Problem(prompt, _fmt(pay), abs_tol=0.011, rel_tol=0) def fin_npv(rng: random.Random) -> Problem: c0 = -rng.choice([1000, 5000, 20000, 50000]) flows = [c0] + [round(-c0 * rng.uniform(0.15, 0.45)) for _ in range(rng.randint(3, 6))] r = rng.choice([4, 6, 8, 10, 12]) npv = sum(c / (1 + r / 100) ** t for t, c in enumerate(flows)) prompt = ( f"A project has cash flows {flows} at the end of years 0, 1, 2, ... (year 0 is today). " f"At a {r}% annual discount rate, what is its NPV? Round to 2 decimals." ) return Problem(prompt, _fmt(npv), abs_tol=0.011, rel_tol=0) def fin_fv(rng: random.Random) -> Problem: p = rng.choice([0, 1000, 5000, 10000]) pmt = rng.choice([100, 200, 250, 500]) r = rng.choice([3, 5, 6, 7, 8]) n = rng.choice([5, 10, 20, 25]) i, m = r / 100 / 12, 12 * n fv = p * (1 + i) ** m + pmt * ((1 + i) ** m - 1) / i prompt = ( f"You deposit ${p} now and ${pmt} at the end of every month for {n} years into an account " f"paying {r}% annual interest compounded monthly. What is the balance at the end? Round to 2 decimals." ) return Problem(prompt, _fmt(fv), abs_tol=0.011, rel_tol=1e-6) def fin_bond(rng: random.Random) -> Problem: face = 1000 c = rng.choice([2, 3, 4.5, 5, 6, 8]) y = rng.choice([2.5, 3.5, 4, 5.5, 7, 9]) n = rng.choice([2, 5, 10, 20]) freq = rng.choice([1, 2]) i, k, cpn = y / 100 / freq, n * freq, face * c / 100 / freq price = sum(cpn / (1 + i) ** t for t in range(1, k + 1)) + face / (1 + i) ** k prompt = ( f"A ${face} face-value bond pays a {c}% annual coupon {'semi-annually' if freq == 2 else 'annually'} " f"and matures in {n} years. If the yield to maturity is {y}% (same compounding), what is its " f"price? Round to 2 decimals." ) return Problem(prompt, _fmt(price), abs_tol=0.011, rel_tol=0) def fin_equilibrium(rng: random.Random) -> Problem: b, d = rng.randint(1, 6), rng.randint(1, 6) p_star = rng.randint(5, 60) + rng.choice([0, 0.25, 0.5]) c = rng.randint(0, 50) a = c + (b + d) * p_star tax = rng.choice([0, 0, 2, 3]) if tax: # Per-unit tax on sellers: Qs = c + d (P - t) p = (a - c + d * tax) / (b + d) q = f"After a per-unit tax of {tax} on sellers (so Qs = {c} + {d}(P - {tax})), what is the new equilibrium price buyers pay?" else: p = p_star q = "What is the equilibrium price?" prompt = f"Demand is Qd = {a} - {b}P and supply is Qs = {c} + {d}P. {q} Round to 2 decimals." return Problem(prompt, _fmt(p), abs_tol=0.011, rel_tol=0) def fin_breakeven(rng: random.Random) -> Problem: fixed = rng.choice([12000, 50000, 85000, 240000]) price = rng.randint(20, 200) var = rng.randint(5, price - 5) units = math.ceil(fixed / (price - var)) prompt = ( f"A product sells for ${price} per unit with variable cost ${var} per unit and fixed costs of " f"${fixed}. What is the smallest whole number of units that must be sold to break even " f"(profit >= 0)? Answer with an integer." ) return Problem(prompt, str(units), kind="int") # --------------------------------------------------------------------------- # # Math and formal reasoning # --------------------------------------------------------------------------- # def math_modpow(rng: random.Random) -> Problem: a, b, m = rng.randint(2, 999), rng.randint(10**5, 10**12), rng.choice([97, 1009, 10007, 65537, 10**9 + 7]) return Problem(f"Compute {a}^{b} mod {m}. Answer with an integer.", str(pow(a, b, m)), kind="int") def math_lattice(rng: random.Random) -> Problem: w, h = rng.randint(4, 7), rng.randint(4, 7) blocked = set() while len(blocked) < rng.randint(2, 5): c = (rng.randint(0, w), rng.randint(0, h)) if c not in ((0, 0), (w, h)): blocked.add(c) dp = [[0] * (h + 1) for _ in range(w + 1)] for x in range(w + 1): for y in range(h + 1): if (x, y) in blocked: continue if x == y == 0: dp[x][y] = 1 else: dp[x][y] = (dp[x - 1][y] if x else 0) + (dp[x][y - 1] if y else 0) prompt = ( f"On the integer grid, count the paths from (0,0) to ({w},{h}) that use only unit steps " f"+x or +y and never visit these blocked points: {sorted(blocked)}. Answer with an integer." ) return Problem(prompt, str(dp[w][h]), kind="int") def math_incl_excl(rng: random.Random) -> Problem: n = rng.randint(1000, 100000) a, b = rng.sample([2, 3, 5, 7, 11, 13], 2) c = rng.choice([4, 6, 9, 10, 15, 21]) cnt = sum(1 for k in range(1, n + 1) if (k % a == 0 or k % b == 0) and k % c != 0) prompt = ( f"How many integers k with 1 <= k <= {n} are divisible by {a} or by {b}, but not divisible " f"by {c}? Answer with an integer." ) return Problem(prompt, str(cnt), kind="int") def math_sat_count(rng: random.Random) -> Problem: nv = rng.randint(4, 6) clauses = [] for _ in range(rng.randint(4, 9)): vs = rng.sample(range(1, nv + 1), 3) clauses.append([v if rng.random() < 0.5 else -v for v in vs]) cnt = 0 for bits in itertools.product([False, True], repeat=nv): if all(any(bits[abs(l) - 1] == (l > 0) for l in cl) for cl in clauses): cnt += 1 fmt = " AND ".join("(" + " OR ".join(("x" if l > 0 else "NOT x") + str(abs(l)) for l in cl) + ")" for cl in clauses) prompt = ( f"Over boolean variables x1..x{nv}, how many of the 2^{nv} assignments satisfy\n{fmt}\n" f"Answer with an integer." ) return Problem(prompt, str(cnt), kind="int") def math_linsys(rng: random.Random) -> Problem: while True: m = [[rng.randint(-6, 6) for _ in range(3)] for _ in range(3)] det = (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])) if det != 0: break sol = [rng.randint(-9, 9) for _ in range(3)] rhs = [sum(m[r][k] * sol[k] for k in range(3)) for r in range(3)] def term(c, v, first): if c == 0: return "" s = ("-" if c < 0 else ("" if first else "+")) + (str(abs(c)) if abs(c) != 1 else "") + v return s if first else " " + s[0] + " " + s[1:] eqs = [] for r in range(3): parts, first = [], True for c, v in zip(m[r], "xyz"): t = term(c, v, first) if t: parts.append(t) first = False eqs.append("".join(parts) + f" = {rhs[r]}") prompt = "Solve the system:\n" + "\n".join(eqs) + "\nAnswer as x, y, z (comma-separated integers)." return Problem(prompt, ", ".join(map(str, sol)), kind="list") def math_trailing_zeros(rng: random.Random) -> Problem: n = rng.randint(50, 10**7) base = rng.choice([10, 10, 2, 5]) p = 5 if base in (10, 5) else 2 z, q = 0, p while q <= n: z += n // q q *= p what = "trailing zeros does n! have in base 10" if base == 10 else f"times does {p} divide n! (the exponent of {p} in n!)" return Problem(f"Let n = {n}. How many {what}? Answer with an integer.", str(z), kind="int") # --------------------------------------------------------------------------- # # Cybersecurity # --------------------------------------------------------------------------- # def cyber_cidr(rng: random.Random) -> Problem: prefix = rng.randint(18, 29) ip = ipaddress.IPv4Address(rng.choice([10 << 24, (172 << 24) | (16 << 16), (192 << 24) | (168 << 16)]) + rng.randint(0, 65535)) net = ipaddress.IPv4Network(f"{ip}/{prefix}", strict=False) q = rng.choice(["network", "broadcast", "hosts", "last"]) if q == "network": return Problem(f"What is the network address of {ip}/{prefix}? Answer with a dotted-quad IPv4 address.", str(net.network_address), kind="text") if q == "broadcast": return Problem(f"What is the broadcast address of {ip}/{prefix}? Answer with a dotted-quad IPv4 address.", str(net.broadcast_address), kind="text") if q == "last": return Problem(f"What is the last usable host address in the subnet containing {ip}/{prefix}? Answer with a dotted-quad IPv4 address.", str(net.broadcast_address - 1), kind="text") return Problem(f"How many usable host addresses are in the subnet containing {ip}/{prefix}? Answer with an integer.", str(net.num_addresses - 2), kind="int") def cyber_authlog(rng: random.Random) -> Problem: ips = [f"{rng.randint(11, 223)}.{rng.randint(0, 255)}.{rng.randint(0, 255)}.{rng.randint(1, 254)}" for _ in range(rng.randint(3, 5))] users = ["root", "admin", "deploy", "ubuntu", "git"] weights = [rng.randint(1, 9) for _ in ips] lines, fails = [], {i: 0 for i in ips} t = dt.datetime(2025, 3, 14, 2, 0, 0) for _ in range(rng.randint(12, 20)): t += dt.timedelta(seconds=rng.randint(1, 90)) ip = rng.choices(ips, weights)[0] u = rng.choice(users) pid = rng.randint(1000, 9999) if rng.random() < 0.75: fails[ip] += 1 inv = "invalid user " if rng.random() < 0.3 else "" lines.append(f"{t:%b %d %H:%M:%S} srv sshd[{pid}]: Failed password for {inv}{u} from {ip} port {rng.randint(30000, 65000)} ssh2") else: lines.append(f"{t:%b %d %H:%M:%S} srv sshd[{pid}]: Accepted publickey for {u} from {ip} port {rng.randint(30000, 65000)} ssh2") best = max(fails.values()) top = [i for i in ips if fails[i] == best] if len(top) != 1 or best == 0: return cyber_authlog(rng) prompt = ( "auth.log excerpt:\n" + "\n".join(lines) + "\nWhich source IP has the most failed password attempts? Answer with the IP address only." ) return Problem(prompt, top[0], kind="text") def cyber_decode(rng: random.Random) -> Problem: words = ["alpha", "bravo", "cipher", "delta", "echo", "falcon", "ghost", "harbor", "ion", "jade"] secret = "FLAG{" + "_".join(rng.sample(words, 3)) + f"_{rng.randint(10, 99)}" + "}" mode = rng.choice(["xor", "b64rot", "b64rev"]) if mode == "xor": key = rng.randint(1, 255) blob = bytes(c ^ key for c in secret.encode()).hex() prompt = f"This hex string is ASCII text XORed with the single-byte key 0x{key:02x}:\n{blob}\nRecover the plaintext." elif mode == "b64rot": blob = base64.b64encode(codecs.encode(secret, "rot13").encode()).decode() prompt = f"This value is base64 of a ROT13-encoded string:\n{blob}\nRecover the original plaintext." else: blob = base64.b64encode(secret[::-1].encode()).decode() prompt = f"This value is base64 of a string that was reversed before encoding:\n{blob}\nRecover the original plaintext." return Problem(prompt + " Answer with the exact plaintext.", secret, kind="text_cs") def cyber_firewall(rng: random.Random) -> Problem: nets = ["10.0.0.0/8", "10.1.0.0/16", "192.168.1.0/24", "0.0.0.0/0", "172.16.5.0/24", "10.1.2.0/24"] rules = [] for _ in range(rng.randint(4, 6)): lo = rng.choice([22, 80, 443, 1000, 3306, 8000]) hi = lo + rng.choice([0, 0, 100, 1000]) rules.append((rng.choice(["ALLOW", "DENY"]), rng.choice(nets), rng.choice(["tcp", "udp", "any"]), lo, hi)) default = rng.choice(["ALLOW", "DENY"]) src = ipaddress.IPv4Address(rng.choice([(10 << 24) | (1 << 16) | (2 << 8), (192 << 24) | (168 << 16) | (1 << 8), (172 << 24) | (16 << 16) | (5 << 8), (8 << 24)]) + rng.randint(1, 254)) port = rng.choice([22, 80, 443, 1050, 3306, 8080, 53]) proto = rng.choice(["tcp", "udp"]) verdict = default for act, net, pr, lo, hi in rules: if src in ipaddress.IPv4Network(net) and pr in ("any", proto) and lo <= port <= hi: verdict = act break rows = "\n".join(f"{k+1}. {a} src={n} proto={p} dport={lo}" + (f"-{hi}" if hi != lo else "") for k, (a, n, p, lo, hi) in enumerate(rules)) prompt = ( f"Firewall rules are evaluated top to bottom; the first match decides, otherwise the default " f"policy {default} applies.\n{rows}\nA {proto} packet arrives from {src} to destination port " f"{port}. Answer ALLOW or DENY." ) return Problem(prompt, verdict, kind="text") def cyber_password_policy(rng: random.Random) -> Problem: min_len = rng.choice([8, 10, 12]) pool = string.ascii_letters + string.digits + "!@#$%^&*" pws = [] for _ in range(rng.randint(6, 10)): n = rng.randint(min_len - 3, min_len + 5) pws.append("".join(rng.choice(pool) for _ in range(n))) def ok(p): return (len(p) >= min_len and any(c.isupper() for c in p) and any(c.islower() for c in p) and any(c.isdigit() for c in p) and any(c in "!@#$%^&*" for c in p)) prompt = ( f"Password policy: at least {min_len} characters and at least one uppercase letter, one " f"lowercase letter, one digit and one symbol from !@#$%^&*. How many of these passwords " f"comply?\n" + "\n".join(pws) + "\nAnswer with an integer." ) return Problem(prompt, str(sum(map(ok, pws))), kind="int") def cyber_hash(rng: random.Random) -> Problem: s = "".join(rng.choice(string.ascii_lowercase + string.digits) for _ in range(rng.randint(6, 14))) algo = rng.choice(["sha256", "md5", "sha1"]) digest = hashlib.new(algo, s.encode()).hexdigest()[:12] prompt = ( f"An integrity manifest lists the first 12 hex characters of the {algo.upper()} digest of the " f"UTF-8 string \"{s}\" (no newline). What are they? Answer with 12 lowercase hex characters." ) return Problem(prompt, digest, kind="text") # --------------------------------------------------------------------------- # # Media and content production # --------------------------------------------------------------------------- # def _tc(frames: int, fps: int) -> str: f = frames % fps s = frames // fps return f"{s // 3600:02d}:{s // 60 % 60:02d}:{s % 60:02d}:{f:02d}" def media_timecode(rng: random.Random) -> Problem: fps = rng.choice([24, 25, 30]) clips = [rng.randint(fps * 3, fps * 400) for _ in range(rng.randint(3, 6))] prompt = ( f"An editor assembles clips of these durations (HH:MM:SS:FF timecode at {fps} fps, " f"non-drop-frame): {', '.join(_tc(c, fps) for c in clips)}. What is the total running time? " f"Answer in HH:MM:SS:FF." ) return Problem(prompt, _tc(sum(clips), fps), kind="text") def media_filesize(rng: random.Random) -> Problem: vk = rng.choice([2500, 5000, 8000, 12000, 20000]) ak = rng.choice([128, 192, 256, 320]) secs = rng.randint(30, 5400) mb = (vk + ak) * 1000 * secs / 8 / 1e6 prompt = ( f"A video is encoded at a constant {vk} kbps for video plus {ak} kbps for audio " f"(1 kbps = 1000 bit/s) and runs {secs // 60} min {secs % 60} s. Ignoring container " f"overhead, what is the file size in megabytes (1 MB = 10^6 bytes)? Round to 1 decimal." ) return Problem(prompt, _fmt(mb, 1), abs_tol=0.1) def media_scale(rng: random.Random) -> Problem: w0, h0 = rng.choice([(1920, 1080), (1280, 720), (3840, 2160), (1080, 1920), (1440, 1080), (2560, 1080), (720, 576)]) w1 = rng.choice([426, 640, 854, 1000, 1080, 1366, 1600]) h = w1 * h0 / w0 h_even = int(2 * round(h / 2)) prompt = ( f"Scale a {w0}x{h0} video to width {w1}, preserving aspect ratio. The encoder needs an even " f"height, so round the exact height to the nearest even integer. What height do you use?" ) return Problem(prompt, str(h_even), kind="int") def media_srt_shift(rng: random.Random) -> Problem: ms = rng.randint(5_000, 5_400_000) shift = rng.choice([-1, 1]) * rng.randint(250, 90_000) if ms + shift < 0: shift = -shift def fmt(t): return f"{t // 3_600_000:02d}:{t // 60_000 % 60:02d}:{t // 1000 % 60:02d},{t % 1000:03d}" prompt = ( f"A subtitle cue starts at {fmt(ms)} (SRT format HH:MM:SS,mmm). The audio is out of sync, so " f"every cue must be shifted by {shift:+d} ms. What is the cue's new start time? Answer in " f"HH:MM:SS,mmm." ) return Problem(prompt, fmt(ms + shift), kind="text") _SMALL = {"a", "an", "the", "and", "but", "or", "for", "nor", "on", "at", "to", "by", "of", "in"} _WORDS = ["night", "of", "the", "living", "code", "and", "a", "river", "in", "winter", "to", "city", "for", "the", "lost", "by", "an", "empire", "on", "fire", "but", "nor", "music", "at", "dawn"] def media_title_case(rng: random.Random) -> Problem: words = [rng.choice(_WORDS) for _ in range(rng.randint(5, 9))] if rng.random() < 0.5: words = [w.upper() if rng.random() < 0.3 else w for w in words] out = [] for k, w in enumerate(words): lw = w.lower() out.append(lw if lw in _SMALL and 0 < k < len(words) - 1 else lw.capitalize()) prompt = ( "House style for headlines: capitalize the first letter of every word and lowercase the rest, " "except these small words, which are all lowercase unless they are the first or last word: " f"{', '.join(sorted(_SMALL))}.\nApply it to: {' '.join(words)}\nAnswer with the styled headline." ) return Problem(prompt, " ".join(out), kind="text_cs") def media_word_stats(rng: random.Random) -> Problem: vocab = ["story", "camera", "light", "frame", "audience", "editor", "sound", "colour", "narrative", "scene", "cut", "pace", "rhythm", "shot", "director", "moment", "visual", "music", "tone"] words = [rng.choice(vocab) for _ in range(rng.randint(30, 60))] text = " ".join(words).capitalize() + "." k = rng.choice([5, 6, 7]) n = sum(1 for w in words if len(w) >= k) prompt = ( f"Copy for a caption:\n{text}\nHow many words in it have at least {k} letters? " f"Answer with an integer." ) return Problem(prompt, str(n), kind="int") # --------------------------------------------------------------------------- # # Registry # --------------------------------------------------------------------------- # FAMILIES: dict[str, list[Callable[[random.Random], Problem]]] = { "software_engineering": [se_topo_order, se_semver, se_rle, se_json_query, se_regex_count], "industrial_systems": [ind_oee, ind_tank, ind_circuit, ind_johnson, ind_eoq, ind_bottleneck], "natural_science": [sci_halflife, sci_projectile, sci_gas, sci_stoich, sci_genetics, sci_dilution], "office_work": [off_business_days, off_meeting, off_pivot, off_expenses, off_dedupe], "finance_economics": [fin_loan, fin_npv, fin_fv, fin_bond, fin_equilibrium, fin_breakeven], "math_reasoning": [math_modpow, math_lattice, math_incl_excl, math_sat_count, math_linsys, math_trailing_zeros], "cybersecurity": [cyber_cidr, cyber_authlog, cyber_decode, cyber_firewall, cyber_password_policy, cyber_hash], "media_production": [media_timecode, media_filesize, media_scale, media_srt_shift, media_title_case, media_word_stats], } TASK_IDS = list(FAMILIES) + ["mixed"] def generate(task_id: str, rng: random.Random) -> tuple[str, Problem]: family = task_id if task_id in FAMILIES else rng.choice(list(FAMILIES)) gen = rng.choice(FAMILIES[family]) return f"{family}/{gen.__name__}", gen(rng)