Skip to content

Instantly share code, notes, and snippets.

@jackdreilly
Created January 30, 2021 11:06
Show Gist options
  • Save jackdreilly/24dedddc623ea7575e2b393db5dce067 to your computer and use it in GitHub Desktop.
Save jackdreilly/24dedddc623ea7575e2b393db5dce067 to your computer and use it in GitHub Desktop.
from parse import parse
store = {}
zeroer, orer = None, None
with open("data/14.txt") as fn:
for line in fn.readlines():
line = line.strip()
r = parse("mem[{}] = {}", line)
if r:
i, v = map(int, r)
store[i] = (v & zeroer) | orer
if not r:
(mask,) = parse("mask = {}", line)
zeroer = int("0b" + "".join("1" if x == "X" else "0" for x in mask), 2)
orer = int("0b" + "".join("0" if x in "X0" else "1" for x in mask), 2)
print(sum(store.values()))
from parse import parse
store = {}
def looper(ander, orer, child):
if not len(child):
yield tuple(int("0b" + x, 2) for x in (ander, orer))
return
letter, rest = child[0], child[1:]
if letter == "X":
for b in ("0", "1"):
yield from looper(ander + b, orer + b, rest)
return
yield from looper(ander + "1", orer + letter, rest)
with open("data/14.txt") as fn:
for line in fn.readlines():
r = parse("mem[{}] = {}", line.strip())
if r:
i, v = map(int, r)
for ander, orer in masks:
store[(i & ander) | orer] = v
continue
masks = list(looper("", "", parse("mask = {}", line.strip())[0]))
print(sum(store.values()))
starts = [0,13,16,17,1,10,6]
nums = {v: k for k, v in enumerate(starts[:-1])}
last = starts[-1]
for i in range(len(nums), 30000000 - 1):
next = 0 if last not in nums else i - nums[last]
nums[last] = i
last = next
print(last)
from parse import parse
import itertools
import math
with open("data/16.txt") as fn:
ranges = []
mine = None
while True:
line = fn.readline().strip()
if not line:
fn.readline()
mine = list(map(int, fn.readline().strip().split(",")))
fn.readline()
fn.readline()
break
p = parse("{}: {}-{} or {}-{}", line)
ranges.append((p[0], list(map(int, p[1:]))))
theirs = [list(map(int, line.strip().split(","))) for line in fn.readlines()]
keepers = [
x
for x in theirs
if all(any(a <= y <= b or c <= y <= d for _, (a, b, c, d) in ranges) for y in x)
] + [mine]
zips = list(zip(*keepers))
candidates = {
k: tuple(
i for i, vs in enumerate(zips) if all(a <= y <= b or c <= y <= d for y in vs)
)
for k, (a, b, c, d) in ranges
}
inverted = {
k: {b for _, b in v}
for k, v in itertools.groupby(
sorted(
((v, k) for k, vs in candidates.items() for v in vs), key=lambda a: a[0]
),
lambda a: a[0],
)
}
sln = {}
for k, v in sorted(inverted.items(), key=lambda a: len(a[1])):
sln[next(iter(v.difference(set(sln.keys()))))] = k
print(math.prod(mine[i] for k, i in sln.items() if "departure" in k))
with open("data/17.txt") as fn:
r = fn.read().strip()
dim = 5
cubes = {
(x, y) + tuple([0] * (dim - 2))
for x, row in enumerate(r.split("\n"))
for y, col in enumerate(row)
if col == "#"
}
def perms(i):
if not i:
yield tuple()
return
for j in range(-1, 2):
for p in perms(i - 1):
yield (j, *p)
_perms = list(perms(dim))
perms = lambda cube: {tuple(map(sum, zip(cube, perm))) for perm in _perms}
for _ in range(6):
cubes = {
cube
for ct, cube in [
(len(perms(cube).intersection(cubes)), cube)
for cube in {perm_cube for cube in cubes for perm_cube in perms(cube)}
]
if (cube in cubes and ct in {3, 4}) or ct == 3
}
print(len(cubes))
with open("data/18.txt") as fn:
r = [x.strip() for x in fn.readlines()]
class Stack:
def __init__(self, parent=None):
self.l = []
self.parent = parent
self.v = None
self.op = None
def run(self, x):
if not self.op:
self.v = x
return
if self.op == "*":
self.v *= x
return
self.v += x
def child(self):
self.l.append(Stack(self))
return self.l[-1]
def construct(self):
return [x.construct() if isinstance(x, Stack) else x for x in self.l]
def solve(x):
stack = Stack()
while len(x):
c, o = x.find(")"), x.find("(")
if c < 0 and o < 0:
s = [y.strip() for y in x.split(" ")]
for ss in s:
if not len(ss):
continue
if ss in {"+", "*"}:
stack.op = ss
continue
stack.run(int(ss))
break
c, o = [99999 if x < 0 else x for x in (c, o)]
if min(o, c) > 0:
s = [y.strip() for y in x[: min(o, c)].split(" ")]
for ss in s:
if not len(ss):
continue
if ss in {"+", "*"}:
stack.op = ss
continue
stack.run(int(ss))
x = x[min(o, c) + 1 :]
if o < c:
stack = stack.child()
continue
stack.parent.run(stack.v)
stack = stack.parent
return stack.v
print(sum(map(solve, r)))
with open("data/18.txt") as fn:
r = [x.strip() for x in fn.readlines()]
class Stack:
def __init__(self, parent=None):
self.l = []
self.parent = parent
self.v = None
self.op = None
def run(self, x):
if not self.op:
self.v = x
return
if self.op == "*":
self.v *= x
return
self.v += x
def child(self):
self.l.append(Stack(self))
return self.l[-1]
def construct(self):
return [x.construct() if isinstance(x, Stack) else x for x in self.l]
def find_nth(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start + len(needle))
n -= 1
return start
def rewrite(x):
for i in range(len([1 for xx in x if xx == "+"])):
j = find_nth(x, "+", i+1)
l, r = j, j
brace = 0
seal = False
while l != 0 and (brace != 0 or (str(x[l]) not in "1234567890" and not seal)):
if x[l] == ")":
brace += 1
seal = True
if x[l] == "(":
brace -= 1
seal = True
l -= 1
while l != 0 and x[l] in "1234567890":
l -= 1
brace = 0
seal = False
while r != len(x) and (brace != 0 or (str(x[r]) not in "1234567890" and not seal)):
if x[r] == ")":
brace += 1
seal = True
if x[r] == "(":
brace -= 1
seal = True
r += 1
while r != len(x) and x[r] in "1234567890":
r += 1
print(i, j, l, r)
x = f"{x[:l]} ({x[l:j-1]} + {x[j+1:r]}) {x[r:]}"
print(x)
return x
def solve(x):
stack = Stack()
while len(x):
c, o = x.find(")"), x.find("(")
if c < 0 and o < 0:
s = [y.strip() for y in x.split(" ")]
for ss in s:
if not len(ss):
continue
if ss in {"+", "*"}:
stack.op = ss
continue
stack.run(int(ss))
break
c, o = [99999 if x < 0 else x for x in (c, o)]
if min(o, c) > 0:
s = [y.strip() for y in x[: min(o, c)].split(" ")]
for ss in s:
if not len(ss):
continue
if ss in {"+", "*"}:
stack.op = ss
continue
stack.run(int(ss))
x = x[min(o, c) + 1 :]
if o < c:
stack = stack.child()
continue
stack.parent.run(stack.v)
stack = stack.parent
return stack.v
print(sum(map(solve, map(rewrite,r))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment