"""65 independent domain algorithms used by the evaluator's reference projects.""" from __future__ import annotations import calendar import collections import csv import datetime as dt import decimal import fnmatch import hashlib import heapq import io import itertools import json import math import re import statistics import urllib.parse def solve(name: str, x: dict): return globals()["solve_" + name](x) def solve_word_frequency(x): words = re.findall(r"[a-z0-9]+", x["text"].lower()) counts = collections.Counter(words) return [ {"word": w, "count": n} for w, n in sorted(counts.items(), key=lambda p: (-p[1], p[0])) ] def solve_slug_registry(x): used, out = set(), [] for title in x["titles"]: root = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-") or "item" slug, i = root, 2 while slug in used: slug, i = f"{root}-{i}", i + 1 used.add(slug) out.append(slug) return out def solve_run_length(x): return [[char, len(list(group))] for char, group in itertools.groupby(x["text"])] def solve_bracket_audit(x): stack = [] for i, c in enumerate(x["text"]): if c in "([{": stack.append((c, i)) elif c in ")]}": if not stack or "([{".index(stack[-1][0]) != ")]}".index(c): return {"balanced": False, "position": i} stack.pop() return {"balanced": not stack, "position": stack[-1][1] if stack else None} def solve_text_wrap(x): lines, line = [], "" for word in x["text"].split(): if line and len(line) + 1 + len(word) > x["width"]: lines.append(line) line = "" line = line + " " + word if line else word if line: lines.append(line) return lines def solve_ngram_index(x): tokens, n = x["tokens"], x["n"] found = collections.defaultdict(list) for i in range(len(tokens) - n + 1): found[tuple(tokens[i : i + n])].append(i) return [{"tokens": list(k), "positions": found[k]} for k in sorted(found)] def solve_glob_filter(x): return sorted({p for p in x["paths"] if fnmatch.fnmatchcase(p, x["pattern"])}) def solve_edit_distance(x): a, b = x["a"], x["b"] row = list(range(len(b) + 1)) for i, char in enumerate(a, 1): nxt = [i] for j, other in enumerate(b, 1): nxt.append(min(nxt[-1] + 1, row[j] + 1, row[j - 1] + (char != other))) row = nxt return row[-1] def solve_roman_codec(x): n, out = x["number"], "" for value, symbol in [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ]: q, n = divmod(n, value) out += symbol * q return out def solve_caesar_cipher(x): out = "" for c in x["text"]: base = ord("a") if "a" <= c <= "z" else ord("A") if "A" <= c <= "Z" else None out += chr((ord(c) - base + x["shift"]) % 26 + base) if base is not None else c return out def solve_csv_records(x): rows = list(csv.reader(io.StringIO(x["csv"]))) return [dict(zip(rows[0], row)) for row in rows[1:]] if rows else [] def solve_record_query(x): rows = [ r for r in x["rows"] if all(k in r and r[k] == v for k, v in x["where"].items()) ] return [{k: r.get(k) for k in x["select"]} for r in rows] def solve_inner_join(x): return [ {"left": a, "right": b} for a in x["left"] for b in x["right"] if x["key"] in a and x["key"] in b and a[x["key"]] == b[x["key"]] ] def solve_group_totals(x): groups = collections.defaultdict(list) for row in x["rows"]: groups[row[x["group"]]].append(row[x["value"]]) return [ {"key": k, "count": len(groups[k]), "sum": sum(groups[k])} for k in sorted(groups) ] def solve_json_flatten(x): out = {} def walk(value, path): if isinstance(value, dict) and value: for k in sorted(value): walk(value[k], path + "/" + k.replace("~", "~0").replace("/", "~1")) elif isinstance(value, list) and value: for i, child in enumerate(value): walk(child, path + "/" + str(i)) else: out[path] = value walk(x["value"], "") return out def solve_merge_patch(x): def merge(target, patch): if not isinstance(patch, dict): return patch out = dict(target) if isinstance(target, dict) else {} for k, v in patch.items(): if v is None: out.pop(k, None) else: out[k] = merge(out.get(k), v) return out return merge(x["target"], x["patch"]) def solve_json_pointer(x): value = x["value"] if x["pointer"] == "": return {"found": True, "value": value} try: for token in x["pointer"][1:].split("/"): token = token.replace("~1", "/").replace("~0", "~") if isinstance(value, list): if not re.fullmatch(r"0|[1-9][0-9]*", token): raise KeyError(token) value = value[int(token)] elif isinstance(value, dict): value = value[token] else: raise KeyError(token) return {"found": True, "value": value} except (KeyError, IndexError): return {"found": False, "value": None} def solve_dedupe_records(x): seen, out = set(), [] for row in x["rows"]: key = json.dumps( [row.get(k) for k in x["keys"]], sort_keys=True, separators=(",", ":") ) if key not in seen: out.append(row) seen.add(key) return out def solve_pivot_table(x): cells = collections.defaultdict(int) rows, cols = set(), set() for item in x["rows"]: r, c = item[x["row"]], item[x["column"]] rows.add(r) cols.add(c) cells[r, c] += item[x["value"]] rows, cols = sorted(rows), sorted(cols) return { "rows": rows, "columns": cols, "values": [[cells[r, c] for c in cols] for r in rows], } def solve_schema_check(x): types = { "string": lambda v: isinstance(v, str), "integer": lambda v: type(v) is int, "number": lambda v: type(v) in (int, float), "boolean": lambda v: type(v) is bool, "array": lambda v: isinstance(v, list), "object": lambda v: isinstance(v, dict), "null": lambda v: v is None, } errors = [] for key in sorted(x["schema"]): rule = x["schema"][key] if key not in x["value"]: if rule["required"]: errors.append({"field": key, "error": "required"}) elif not types[rule["type"]](x["value"][key]): errors.append({"field": key, "error": "type"}) return errors def solve_interval_union(x): out = [] for start, end in sorted(x["intervals"]): if out and start <= out[-1][1]: out[-1][1] = max(end, out[-1][1]) else: out.append([start, end]) return out def solve_interval_gaps(x): low, high = x["bounds"] out, cursor = [], low for a, b in solve_interval_union(x): a, b = max(low, a), min(high, b) if a > b: continue if a > cursor: out.append([cursor, a]) cursor = max(cursor, b) if cursor < high: out.append([cursor, high]) return out def solve_booking_peak(x): events = collections.defaultdict(int) for start, end in x["bookings"]: if start < end: events[start] += 1 events[end] -= 1 current = peak = 0 at = None for t, delta in sorted(events.items()): current += delta if current > peak: peak, at = current, t return {"peak": peak, "at": at} def solve_business_days(x): day, end = dt.date.fromisoformat(x["start"]), dt.date.fromisoformat(x["end"]) holidays, out = set(x["holidays"]), [] while day < end: if day.weekday() < 5 and day.isoformat() not in holidays: out.append(day.isoformat()) day += dt.timedelta(days=1) return out def solve_calendar_month(x): return calendar.Calendar(firstweekday=0).monthdayscalendar(x["year"], x["month"]) def solve_moving_average(x): return [ sum(x["values"][i : i + x["window"]]) / x["window"] for i in range(len(x["values"]) - x["window"] + 1) ] def solve_statistics(x): values = x["values"] if not values: return { "count": 0, "min": None, "max": None, "mean": None, "median": None, "variance": None, } return { "count": len(values), "min": min(values), "max": max(values), "mean": statistics.mean(values), "median": statistics.median(values), "variance": statistics.pvariance(values), } def solve_histogram(x): edges = x["edges"] bins, under, over = [0] * (len(edges) - 1), 0, 0 for v in x["values"]: if v < edges[0]: under += 1 elif v >= edges[-1]: over += 1 else: for i in range(len(bins)): if edges[i] <= v < edges[i + 1]: bins[i] += 1 break return {"counts": bins, "underflow": under, "overflow": over} def solve_matrix_product(x): return [ [sum(a * b for a, b in zip(row, col)) for col in zip(*x["b"])] for row in x["a"] ] def solve_polynomial(x): return [ sum(c * value**i for i, c in enumerate(x["coefficients"])) for value in x["points"] ] def solve_prime_factors(x): n, out, factor = x["number"], [], 2 while factor * factor <= n: count = 0 while n % factor == 0: n //= factor count += 1 if count: out.append([factor, count]) factor += 1 if n > 1: out.append([n, 1]) return out def solve_base_convert(x): chars = "0123456789abcdefghijklmnopqrstuvwxyz" n = int(x["digits"], x["from_base"]) sign, n = ("-" if n < 0 else ""), abs(n) out = "" while n: n, rem = divmod(n, x["to_base"]) out = chars[rem] + out return sign + (out or "0") def solve_money_split(x): weights, amount = x["weights"], x["amount"] total = sum(weights) shares = [amount * w // total for w in weights] order = sorted( range(len(weights)), key=lambda i: (-(amount * weights[i] % total), i) ) for i in order[: amount - sum(shares)]: shares[i] += 1 return shares def solve_invoice_total(x): D = decimal.Decimal subtotal = sum( (D(item["price"]) * item["quantity"] for item in x["items"]), D(0) ).quantize(D(".01"), rounding=decimal.ROUND_HALF_UP) tax = (subtotal * D(x["tax_rate"])).quantize( D(".01"), rounding=decimal.ROUND_HALF_UP ) return { "subtotal": f"{subtotal:.2f}", "tax": f"{tax:.2f}", "total": f"{subtotal + tax:.2f}", } def solve_coin_change(x): amount, coins = x["amount"], sorted(set(x["coins"])) dp = [0] + [amount + 1] * amount for n in range(1, amount + 1): dp[n] = min([dp[n - c] + 1 for c in coins if c <= n] or [amount + 1]) return None if dp[amount] > amount else dp[amount] def graph(x, weighted=False, directed=True): adj = {node: [] for node in x["nodes"]} for edge in x["edges"]: a, b = edge[:2] adj[a].append((b, edge[2]) if weighted else b) if not directed: adj[b].append((a, edge[2]) if weighted else a) return adj def solve_graph_reach(x): adj, found = graph(x), {x["start"]} todo = [x["start"]] while todo: for node in adj[todo.pop()]: if node not in found: found.add(node) todo.append(node) return sorted(found) def solve_shortest_path(x): adj = graph(x, weighted=True) distances = {x["start"]: 0} queue = [(0, x["start"])] while queue: distance, node = heapq.heappop(queue) if distances[node] != distance: continue for other, weight in adj[node]: alt = distance + weight if alt < distances.get(other, math.inf): distances[other] = alt heapq.heappush(queue, (alt, other)) return {node: distances.get(node) for node in sorted(x["nodes"])} def solve_topological_order(x): adj, indegree = graph(x), dict.fromkeys(x["nodes"], 0) for edges in adj.values(): for node in edges: indegree[node] += 1 queue = [n for n in indegree if indegree[n] == 0] heapq.heapify(queue) out = [] while queue: node = heapq.heappop(queue) out.append(node) for other in adj[node]: indegree[other] -= 1 if indegree[other] == 0: heapq.heappush(queue, other) return out if len(out) == len(adj) else None def solve_connected_components(x): adj, seen, out = graph(x, directed=False), set(), [] for node in sorted(adj): if node in seen: continue group, todo = [], [node] seen.add(node) while todo: n = todo.pop() group.append(n) for other in adj[n]: if other not in seen: seen.add(other) todo.append(other) out.append(sorted(group)) return out def solve_grid_route(x): grid, start, end = x["grid"], tuple(x["start"]), tuple(x["end"]) seen, queue = {start}, collections.deque([(start, 0)]) if grid[start[0]][start[1]] == "#" or grid[end[0]][end[1]] == "#": return None while queue: (r, c), distance = queue.popleft() if (r, c) == end: return distance for nr, nc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]: if ( 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#" and (nr, nc) not in seen ): seen.add((nr, nc)) queue.append(((nr, nc), distance + 1)) return None def solve_tree_outline(x): children = collections.defaultdict(list) for node in x["nodes"]: children[node["parent"]].append(node["id"]) out = [] def walk(parent, depth): for node in sorted(children[parent]): out.append({"id": node, "depth": depth}) walk(node, depth + 1) walk(None, 0) return out def solve_dependency_build(x): deps, out, active, done = x["dependencies"], [], set(), set() def visit(node): if node in active: raise ValueError("cycle") if node in done: return active.add(node) for other in sorted(deps[node]): visit(other) active.remove(node) done.add(node) out.append(node) try: for target in sorted(set(x["targets"])): visit(target) except ValueError: return None return out def solve_path_normalize(x): out = [] for path in x["paths"]: parts = [] for part in path.split("/"): if part in ("", "."): continue if part == "..": if parts: parts.pop() else: parts.append(part) out.append("/" + "/".join(parts)) return out def solve_url_query(x): out = collections.defaultdict(list) for k, v in urllib.parse.parse_qsl(x["query"], keep_blank_values=True): out[k].append(v) return dict(out) def solve_version_sort(x): def key(v): core, _, pre = v.partition("-") parts = tuple(map(int, core.split("."))) ids = ( tuple((0, int(p)) if p.isdigit() else (1, p) for p in pre.split(".")) if pre else () ) return parts, not bool(pre), ids return sorted(x["versions"], key=key) def solve_lru_trace(x): cache, hits, misses = collections.OrderedDict(), 0, 0 for key in x["accesses"]: if key in cache: hits += 1 cache.move_to_end(key) else: misses += 1 if x["capacity"]: cache[key] = True if len(cache) > x["capacity"]: cache.popitem(last=False) return {"hits": hits, "misses": misses, "keys": list(cache)} def solve_rate_limit(x): history, out = collections.defaultdict(collections.deque), [] for event in x["events"]: times = history[event["key"]] while times and times[0] <= event["time"] - x["window"]: times.popleft() allowed = len(times) < x["limit"] if allowed: times.append(event["time"]) out.append(allowed) return out def solve_priority_queue(x): queue, out, seq = [], [], 0 for event in x["events"]: if event["op"] == "push": heapq.heappush(queue, (event["priority"], seq, event["value"])) seq += 1 else: out.append(heapq.heappop(queue)[2] if queue else None) return {"popped": out, "remaining": [v for _, _, v in sorted(queue)]} def solve_round_robin(x): quantum = x["quantum"] queue = collections.deque((job["id"], job["duration"]) for job in x["jobs"]) clock, slices, completion = 0, [], {} while queue: key, left = queue.popleft() used = min(quantum, left) slices.append({"id": key, "start": clock, "end": clock + used}) clock += used if left > used: queue.append((key, left - used)) else: completion[key] = clock return {"slices": slices, "completion": completion} def solve_inventory_ledger(x): stock, rejected = {}, [] for i, event in enumerate(x["events"]): new = stock.get(event["sku"], 0) + event["delta"] if new < 0: rejected.append(i) else: stock[event["sku"]] = new return {"stock": stock, "rejected": rejected} def solve_bank_ledger(x): balances, rejected = dict(x["balances"]), [] for i, t in enumerate(x["transfers"]): if ( t["from"] not in balances or t["to"] not in balances or balances[t["from"]] < t["amount"] ): rejected.append(i) else: balances[t["from"]] -= t["amount"] balances[t["to"]] += t["amount"] return {"balances": balances, "rejected": rejected} def solve_ballot_count(x): counts = dict.fromkeys(x["candidates"], 0) invalid = 0 for vote in x["votes"]: if vote in counts: counts[vote] += 1 else: invalid += 1 return { "ranking": [ {"candidate": c, "votes": n} for c, n in sorted(counts.items(), key=lambda p: (-p[1], p[0])) ], "invalid": invalid, } def solve_search_rank(x): terms = set(re.findall(r"[a-z0-9]+", x["query"].lower())) scored = [] for doc in x["documents"]: counts = collections.Counter(re.findall(r"[a-z0-9]+", doc["text"].lower())) score = sum(counts[t] for t in terms) if score: scored.append({"id": doc["id"], "score": score}) return sorted(scored, key=lambda r: (-r["score"], r["id"])) def solve_log_summary(x): counts = collections.Counter(event["level"] for event in x["events"]) errors = [e["message"] for e in x["events"] if e["level"] == "ERROR"] return {"counts": dict(counts), "errors": errors} def solve_uptime_report(x): intervals = solve_interval_union( { "intervals": [ [max(a, x["start"]), min(b, x["end"])] for a, b in x["downtime"] if max(a, x["start"]) < min(b, x["end"]) ] } ) down = sum(b - a for a, b in intervals) return {"down": down, "up": x["end"] - x["start"] - down} def solve_segment_intersection(x): a, b, c, d = x["a"], x["b"], x["c"], x["d"] def cross(p, q, r): return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) def on(p, q, r): return ( cross(p, q, r) == 0 and min(p[0], q[0]) <= r[0] <= max(p[0], q[0]) and min(p[1], q[1]) <= r[1] <= max(p[1], q[1]) ) u, v, w, z = cross(a, b, c), cross(a, b, d), cross(c, d, a), cross(c, d, b) return ( (u * v < 0 and w * z < 0) or on(a, b, c) or on(a, b, d) or on(c, d, a) or on(c, d, b) ) def solve_polygon_area(x): pts = x["points"] return ( abs(sum(a[0] * b[1] - a[1] * b[0] for a, b in zip(pts, pts[1:] + pts[:1]))) / 2 if pts else 0 ) def solve_skyline(x): buildings = x["buildings"] points, prev = [], 0 for t in sorted({v for a, b, _ in buildings for v in (a, b)}): height = max([h for a, b, h in buildings if a <= t < b] or [0]) if height != prev: points.append([t, height]) prev = height return points def solve_knapsack(x): capacity = x["capacity"] dp = [0] * (capacity + 1) for item in x["items"]: for w in range(capacity, item["weight"] - 1, -1): dp[w] = max(dp[w], dp[w - item["weight"]] + item["value"]) return dp[capacity] def solve_task_selection(x): end, out = None, [] for job in sorted(x["tasks"], key=lambda j: (j["end"], j["start"], j["id"])): if end is None or job["start"] >= end: out.append(job["id"]) end = job["end"] return out def solve_sequence_diff(x): a, b = x["a"], x["b"] dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)] for i in range(len(a) - 1, -1, -1): for j in range(len(b) - 1, -1, -1): dp[i][j] = ( 1 + dp[i + 1][j + 1] if a[i] == b[j] else max(dp[i + 1][j], dp[i][j + 1]) ) i = j = 0 out = [] while i < len(a) or j < len(b): if i < len(a) and j < len(b) and a[i] == b[j]: out.append(["keep", a[i]]) i, j = i + 1, j + 1 elif i < len(a) and (j == len(b) or dp[i + 1][j] >= dp[i][j + 1]): out.append(["delete", a[i]]) i += 1 else: out.append(["insert", b[j]]) j += 1 return out def solve_finite_automaton(x): transitions = {(t["from"], t["symbol"]): t["to"] for t in x["transitions"]} out = [] for word in x["words"]: state = x["start"] for symbol in word: state = transitions.get((state, symbol)) if state is None: break out.append(state in x["accepting"]) return out def solve_content_manifest(x): return [ { "path": path, "bytes": len(text.encode("utf-8")), "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), } for path, text in sorted(x["files"].items()) ] def solve_cellular_automaton(x): cells = {tuple(p) for p in x["live"]} for _ in range(x["steps"]): neighbors = collections.Counter( (r + dr, c + dc) for r, c in cells for dr in (-1, 0, 1) for dc in (-1, 0, 1) if (dr, dc) != (0, 0) ) cells = {p for p, n in neighbors.items() if n == 3 or n == 2 and p in cells} return [list(p) for p in sorted(cells)] def solve_expression_eval(x): stack = [] for token in x["tokens"]: if token not in ("+", "-", "*", "/"): stack.append(int(token)) else: b, a = stack.pop(), stack.pop() if token == "+": stack.append(a + b) elif token == "-": stack.append(a - b) elif token == "*": stack.append(a * b) else: stack.append((abs(a) // abs(b)) * (-1 if (a < 0) != (b < 0) else 1)) return stack[0]