Advertisement
kupuguy

Advent Of Code 2024 Day 23

Dec 23rd, 2024
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | Source Code | 0 0
  1. from pathlib import Path
  2. from collections import defaultdict
  3.  
  4.  
  5. def parse(input: str) -> list[tuple[str, str]]:
  6.     return [s.split("-", 1) for s in input.splitlines()]
  7.  
  8.  
  9. def part1(data: list[tuple[str, str]]) -> int:
  10.     connections: dict[str, set[str]] = defaultdict(set)
  11.     for a, b in data:
  12.         connections[a].add(b)
  13.         connections[b].add(a)
  14.  
  15.     groups: set[frozenset[str]] = set()
  16.     for a in connections:
  17.         for b in connections[a]:
  18.             for c in (connections[a] & connections[b]) - {a, b}:
  19.                 groups.add(frozenset([a, b, c]))
  20.  
  21.     tcomputers = {a for a in connections if a.startswith("t")}
  22.     tgroups = {g for g in groups if g & tcomputers}
  23.     return len(tgroups)
  24.  
  25.  
  26. def merge_groups(
  27.     groups: set[frozenset[str]], connections: dict[str, set[str]]
  28. ) -> set[frozenset[str]]:
  29.     merged: set[frozenset[str]] = set()
  30.     for g1 in groups:
  31.         mx = max(g1)
  32.         for c in connections:
  33.             if c > mx and (g1 & connections[c]) == g1:
  34.                 merged.add(frozenset(g1 | {c}))
  35.     return merged
  36.  
  37.  
  38. def part2(data: list[str]) -> str:
  39.     connections: dict[str, set[str]] = defaultdict(set)
  40.     for a, b in data:
  41.         connections[a].add(b)
  42.         connections[b].add(a)
  43.  
  44.     groups: set[frozenset[str]] = set()
  45.     for a in connections:
  46.         for b in connections[a]:
  47.             for c in (connections[a] & connections[b]) - {a, b}:
  48.                 groups.add(frozenset([a, b, c]))
  49.     print("triples", len(groups))
  50.  
  51.     while len(groups) > 1:
  52.         merged = merge_groups(groups, connections)
  53.         if merged:
  54.             print(f"{len(merged)=}")
  55.             groups = merged
  56.         else:
  57.             break
  58.     print(f"{len(groups)=}")
  59.     for g in groups:
  60.         return ",".join(sorted(g))
  61.  
  62.  
  63. TEST = parse(Path("input/day23-test.txt").read_text())
  64. assert part1(TEST) == 7
  65. INPUT = parse(Path("input/day23.txt").read_text())
  66. part1_total = part1(INPUT)
  67. print(f"{part1_total=:,}")
  68.  
  69. assert part2(TEST) == "co,de,ka,ta"
  70. part2_total = part2(INPUT)
  71. print(f"{part2_total=}")  # ab,cp,ep,fj,fl,ij,in,ng,pl,qr,rx,va,vf
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement