Skip to content

Commit

Permalink
day 7
Browse files Browse the repository at this point in the history
  • Loading branch information
wimglenn committed Jan 3, 2025
1 parent a107d4e commit 7e008de
Showing 1 changed file with 22 additions and 45 deletions.
67 changes: 22 additions & 45 deletions aoc_wim/aoc2015/q07.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,62 +2,39 @@
--- Day 7: Some Assembly Required ---
https://adventofcode.com/2015/day/7
"""
import operator
import re
from collections import deque

import numpy as np
from aocd import data


# TODO: change to use topological sort

opmap = {
"AND": operator.and_,
"OR": operator.or_,
"LSHIFT": operator.lshift,
"RSHIFT": operator.rshift,
}
def compute(data):
wire = {}

def get(v):
return wire[v] if v in wire else np.uint16(v)

def compute(data):
result = {}

def getval(v):
return result[v] if v in result else np.uint16(v)

lines = [line.split(" -> ") for line in data.splitlines()]

def process_line(line):
left, right = line
left = left.split()
len_left = len(left)
if len_left == 1:
# store
result[right] = getval(left[0])
elif len_left == 2:
# negation
op, val = left
if op != "NOT":
raise Exception
result[right] = ~getval(val)
elif len_left == 3:
a, op, b = left
op = opmap[op]
result[right] = op(getval(a), getval(b))

while lines:
line = lines.pop()
q = deque(data.splitlines())
while q:
line = q.pop()
try:
process_line(line)
match line.split():
case n, "->", w:
wire[w] = get(n)
case "NOT", n, "->", w:
wire[w] = ~get(n)
case x, op, y, "->", w:
f = getattr(np.uint16, f"__{op}__".lower())
wire[w] = f(get(x), get(y))
except (KeyError, ValueError):
lines = [line] + lines
q.appendleft(line)

return result
return wire["a"]


result = compute(data)
result_a = result["a"]
print("answer_a:", result_a)
a = compute(data)
print("answer_a:", a)

new_data = re.sub(r"\n([0-9]+) -> b\n", f"\n{result_a} -> b\n", data)
print("answer_b:", compute(new_data)["a"])
new_data = re.sub(r"\n([0-9]+) -> b\n", f"\n{a} -> b\n", data)
print("answer_b:", compute(new_data))

0 comments on commit 7e008de

Please sign in to comment.