rename stuff

This commit is contained in:
Maya Herrscher committed 2022-12-03 15:08:59 +01:00
1 parent 7c3d439f6e
commit 97ddc36b62
325 files changed
+85

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
import sys
if __name__ == '__main__':
measurements = open(sys.argv[1]).read().strip('\n\n').split('\n')
meas = [int(i) for i in measurements]
# challenge 1
incr = 0
last = 0
for i in meas:
if i > last:
incr += 1
last = i
res1 = str(incr - 1)
print("challenge 1: " + res1 + "\n")
# challenge 2
incr = 0
first = meas[0]
second = meas[1]
third = meas[2]
last = first + second + third
for i in meas[3:]:
first = second
second = third
third = i
nex = first + second + third
if nex > last:
incr += 1
last = nex
res2 = str(incr)
print("challenge 2: " + res2 + "\n")
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
import sys
if __name__ == '__main__':
lines = open(sys.argv[1]).readlines()
dirs = [i.strip('\n').split(" ") for i in lines]
# challenge 1
dep = 0
pos = 0
for d in dirs:
if d[0] == 'forward':
pos += int(d[1])
elif d[0] == 'up':
dep -= int(d[1])
elif d[0] == 'down':
dep += int(d[1])
else:
print(d)
res1 = str(dep * pos)
print("challenge 1:" + res1 + "\n")
# challenge 2
dep = 0
pos = 0
aim = 0
for d in dirs:
if d[0] == 'forward':
pos += int(d[1])
dep += int(d[1]) * aim
elif d[0] == 'up':
aim -= int(d[1])
elif d[0] == 'down':
aim += int(d[1])
else:
print(d)
res2 = str(dep * pos)
print("challenge 2:" + res2 + "\n")
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
import sys
def inverted(i):
if i == 0:
return 1
else:
return 0
def filter(lis, pos, i):
if len(lis) == 1:
return lis
if sum([b[pos] for b in lis]) >= sum([inverted(b[pos]) for b in lis]):
val = i
else:
val = inverted(i)
return [i for i in lis if i[pos] == val]
if __name__ == '__main__':
lines = open(sys.argv[1]).readlines()
bins = [[int(i) for i in list(l.strip('\n'))] for l in lines]
# challenge 1
lis = [0] * len(bins[0])
for i in range(len(bins[0])):
lis[i] = sum([b[i] for b in bins])
g = ''
e = ''
for i in range(len(bins[0])):
if lis[i] > 0.5 * len(lines):
g += '1'
e += '0'
else:
g += '0'
e += '1'
gamma = int(g, 2)
eps = int(e,2)
res1 = str(gamma * eps)
print("challenge 1:" + res1 + "\n")
ox = bins
co2 = bins
# challenge 2
for i in range(len(bins[0])):
ox = filter(ox, i, 1)
co2 = filter(co2, i, 0)
oxr = int(''.join(str(i) for i in ox[0]), 2)
csr = int(''.join(str(i) for i in co2[0]), 2)
res2 = str(oxr * csr)
print("challenge 2:" + res2 + "\n")
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env python3
import sys
def printb(board):
for line in board:
print(str(line[0]) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(line[3]) + ' ' + str(line[4]))
print("\n")
def check_win(board):
for l in board:
if l == ['x' ,'x', 'x', 'x', 'x']:
return True
hit = 0
for i in range(len(board)):
for l in board:
if l[i] == 'x':
hit += 1
if hit == len(board):
return True
hit = 0
return False
def play(boards):
for num in nums:
boards = [mark_board(board, num) for board in boards]
for board in boards:
if check_win(board):
return num * sum([sum([i for i in l if i != 'x']) for l in board])
def play2(boards):
for num in nums:
boards = [mark_board(board, num) for board in boards]
if sum([1 if check_win(board) else 0 for board in boards]) == (len(boards) - 1):
for i in range(len(boards)):
if not check_win(boards[i]):
last = i
if sum([1 if check_win(board) else 0 for board in boards]) == (len(boards)):
if check_win(boards[last]):
board = boards[last]
return num * sum([sum([i for i in l if i != 'x']) for l in board])
def mark_board(board, num):
return [['x' if col == num else col for col in li] for li in board]
if __name__ == '__main__':
lines = open(sys.argv[1]).read().split('\n\n') # or split \n\n or sth similar
nums = [int(i) for i in lines[0].split(',')]
boards = [[[int(n) for n in l.split(' ') if n != ''] for l in li.split('\n')] for li in lines[1:]]
boards = [[l for l in b if l != []] for b in boards]
# challenge 1
res1 = str(play(boards))
print("challenge 1:" + res1 + "\n")
# challenge 2
res2 = str(play2(boards))
print("challenge 2:" + res2 + "\n")
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
import sys
import re
def parse(line):
groups = re.compile(r"(?P<x1>\d+),(?P<y1>\d+) -> (?P<x2>\d+),(?P<y2>\d+)").search(line)
return groups
def calc(x1, y1, x2, y2, mem):
if x1 == x2:
if y1 > y2:
y = y2
y2 = y1
y1 = y
for y in range(y1, y2+1):
if (x1, y) not in mem:
mem[(x1, y)] = 1
else:
mem[(x1, y)] += 1
elif y1 == y2:
if x1 > x2:
x = x2
x2 = x1
x1 = x
for x in range(x1, x2+1):
if (x, y1) not in mem:
mem[(x, y1)] = 1
else:
mem[(x, y1)] += 1
def calc2(x1, y1, x2, y2):
if x1 != x2 and y1 != y2:
if x1 > x2:
dif = x1-x2+1
m1 = -1
else:
dif = x2-x1+1
m1 = 1
if y1 > y2:
m2 = -1
else:
m2 = 1
for i in range(dif):
if (x1+m1*i, y1+m2*i) not in memo2:
memo2[(x1+m1*i, y1+m2*i)] = 1
else:
memo2[(x1+m1*i, y1+m2*i)] += 1
if __name__ == '__main__':
lines = open(sys.argv[1]).readlines()
coords = [tuple(map(int,parse(line).groups())) for line in lines]
# challenge 1
memo = {}
for c in coords:
calc(*c,memo)
res1 = 0
for v in memo.values():
if v > 1:
res1 += 1
print("challenge 1:" + "\n" + str(res1) + "\n")
# challenge 2
memo2 = {}
for c in coords:
calc(*c,memo2)
calc2(*c)
res2 = 0
for v in memo2.values():
if v > 1:
res2 += 1
print("challenge 2:" + "\n" + str(res2) + "\n")
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
import sys
from copy import deepcopy
def sim(lf, days):
nf = {}
for i in range(days):
for k,v in lf.items():
if k == 7:
nf[6] = (nf[6] + v) if 6 in nf else v
elif k == 6:
nf[5] = v
elif k == 0:
nf[8] = v
nf[6] = (nf[6] + v) if 6 in nf else v
else:
nf[k-1] = v
lf = deepcopy(nf)
nf = {}
return sum(lf.values())
if __name__ == '__main__':
lines = open(sys.argv[1]).read().strip('\n\n').split('\n') # or split \n\n or sth similar
nums = [int(i) for i in lines[0].split(",")]
lf1 = {}
lf1[6] = 0
lf1[7] = 0
lf1[8] = 0
for n in nums:
if n not in lf1:
lf1[n] = 1
else:
lf1[n] += 1
lf2 = deepcopy(lf1)
# challenge 1
res1 = str(sim(lf1, 80))
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
res2 = str(sim(lf2, 256))
print("challenge 2:" +"\n" + res2 + "\n")
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
import sys
def fuel(crabs, x):
return sum(abs(c-x) for c in crabs)
def fuel_incr(crabs, x):
return sum(sc[abs(c-x)] for c in crabs)
if __name__ == '__main__':
lines = open(sys.argv[1]).read().strip('\n\n').split('\n') # or split \n\n or sth similar
nums = [int(i) for i in lines[0].split(",")]
# challenge 1
res1 = str(min(fuel(nums, i) for i in range(max(nums))))
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
sc = [0] * (max(nums)+1)
for i in range(max(nums)+1):
sc[i] = sc[i-1] + i
res2 = str(min(fuel_incr(nums, i) for i in range(max(nums))))
print("challenge 2:" +"\n" + res2 + "\n")
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
import sys
def search_num(d, val):
for k,v in d.items():
if val == v:
return str(k)
def decode(inp, out):
nums = {}
for i in sorted(inp, key=len):
if len(i) == 2: nums[1] = set(i)
elif len(i) == 3: nums[7] = set(i)
elif len(i) == 4: nums[4] = set(i)
elif len(i) == 5: #2, 3, 5
if nums[1] <= set(i): nums[3] = set(i)
elif len(i) == 6: #0, 6, 9
if nums[4] <= set(i): nums[9] = set(i)
elif nums[1] <= set(i): nums[0] = set(i)
else: nums[6] = set(i)
elif len(i) == 7: nums[8] = set(i)
for i in inp:
if set(i) not in nums.values():
if set(i) <= nums[6]: nums[5] = set(i)
else: nums[2] = set(i)
return int(''.join([search_num(nums, set(o)) for o in out]))
if __name__ == '__main__':
lines = open(sys.argv[1]).read().strip('\n\n').split('\n') # or split \n\n or sth similar
inp = [i.split(' | ') for i in lines]
inout = [(i[0].split(' '), i[1].split(' ')) for i in inp]
# challenge 1
sums = 0
for _,out in inout:
for o in out:
if len(o) == 2 or len(o) == 3 or len(o) == 4 or len(o) == 7:
sums += 1
res1 = str(sums)
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
res2 = str(sum([decode(i,o) for i,o in inout]))
print("challenge 2:" +"\n" + res2 + "\n")
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
import sys
def risk_level(m, x, y):
adj = []
if x-1 > -1:
adj.append(m[x-1][y])
try: adj.append(m[x+1][y])
except IndexError: pass
if y-1 > -1:
adj.append(m[x][y-1])
try: adj.append(m[x][y+1])
except IndexError: pass
for a in adj:
if a <= m[x][y]:
return 0
return m[x][y] + 1
def basin(m, x, y):
while (x,y) not in bas:
adj = {}
adj[(0,0)] = m[x][y]
if x-1 > -1:
adj[(-1,0)] = m[x-1][y]
try: adj[(1,0)] = m[x+1][y]
except IndexError: pass
if y-1 > -1:
adj[(0,-1)] = m[x][y-1]
try: adj[(0,1)] = m[x][y+1]
except IndexError: pass
mi = min(adj.items(),key=lambda x: x[1])
x += mi[0][0]
y += mi[0][1]
bas[(x,y)] += 1
if __name__ == '__main__':
lines = open(sys.argv[1]).read().strip('\n\n').split('\n') # or split \n\n or sth similar
mp = [[int(i) for i in l] for l in lines]
bas = {}
risk = 0
for x in range(len(mp)):
for y in range(len(mp[0])):
r = risk_level(mp, x, y)
risk += r
if r > 0:
bas[(x,y)] = 0
for x in range(len(mp)):
for y in range(len(mp[0])):
if mp[x][y] != 9:
basin(mp, x, y)
b = sorted(bas.values(), reverse=True)
# challenge 1
res1 = str(risk)
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
res2 = str(b[0]*b[1]*b[2])
print("challenge 2:" +"\n" + res2 + "\n")
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
import sys
from operator import mul
from functools import reduce
def adj(mp, x, y):
adj = {}
if x-1 > -1: adj[(-1,0)] = mp[x-1][y]
if x+1 < len(mp): adj[(1,0)] = mp[x+1][y]
if y-1 > -1: adj[(0,-1)] = mp[x][y-1]
if y+1 < len(mp[0]): adj[(0,1)] = mp[x][y+1]
return adj
def risk(mp, x, y):
ad = adj(mp, x, y).values()
if all(map(lambda i: i > mp[x][y], ad)):
bas[(x,y)] = 0
return mp[x][y] + 1
else: return 0
def basin(mp, x, y):
nex = min(adj(mp, x, y).items(), key=lambda i: i[1])
if (x,y) in bas: (i,j) = (x,y)
elif (x,y) in mem: (i,j) = mem[(x,y)]
else:
(i,j) = basin(mp, x+nex[0][0], y+nex[0][1])
return (i,j)
bas[(i,j)] += 1
return (i,j)
if __name__ == '__main__':
m = [[int(i) for i in l] for l in open(sys.argv[1]).read().strip('\n\n').split('\n')]
bas,mem = {},{}
# challenge 1
res1 = str(sum([sum([risk(m, x, y) for y in range(len(m[0]))]) for x in range(len(m))]))
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
([([basin(m, x, y) for y in range(len(m[0])) if m[x][y] < 9]) for x in range(len(m))])
res2 = str(reduce(mul, sorted(bas.values(), reverse=True)[0:3]))
print("challenge 2:" +"\n" + res2 + "\n")
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
import sys
import statistics
def corr(line):
st = []
for b in line:
if b in match.keys(): st.append(b)
if b in error.keys():
if not (st.pop(), b) in match.items(): return error[b]
return 0
def inc(line):
st, score = [], 0
for b in line:
if b in match.keys(): st.append(b)
if b in comp.keys(): st.pop()
miss = [match[b] for b in st]
for b in reversed(miss):
score *= 5
score += comp[b]
return score
if __name__ == '__main__':
inp = [list(i) for i in open(sys.argv[1]).read().strip('\n\n').split('\n')]
match = {'(': ')', '{': '}', '[': ']', '<': '>'}
# challenge 1
error = {')': 3, ']': 57, '}': 1197, '>': 25137}
res1 = str(sum([corr(line) for line in inp]))
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
comp = {')': 1, ']': 2, '}': 3, '>': 4}
res2 = str(statistics.median([inc(line) for line in inp if corr(line) == 0]))
print("challenge 2:" +"\n" + res2 + "\n")
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
import sys
def flash(octop, x, y):
for i in [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]:
if -1 < y+i[0] < len(octop) and -1 < x+i[1] < len(octop):
if octop[y+i[0]][x+i[1]] > 0: octop[y+i[0]][x+i[1]] += 1
octop[y][x] = 0
return octop
def flashable(octo):
for y in octo:
for x in y:
if x > 9:
return True
return False
def step(octo):
nex = [[x+1 for x in y] for y in octo]
flashs = 0
while flashable(nex):
for x in range(len(octo[0])):
for y in range(len(octo)):
if nex[y][x] > 9:
nex = flash(nex,x,y)
flashs += 1
return nex, flashs
if __name__ == '__main__':
lines = open(sys.argv[1]).read().strip('\n\n').split('\n') # or split \n\n or sth similar
octos = [[int(i) for i in l] for l in lines]
# challenge 1
flashes, i = 0, 0
while True:
i += 1
octos, f = step(octos)
if(i <= 100):
flashes += f
if sum([sum([1 for x in range(len(octos[0])) if octos[y][x] == 0]) for y in range(len(octos))]) == 100:
first = i
break
res1 = str(flashes)
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
res2 = str(first)
print("challenge 2:" +"\n" + res2 + "\n")
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
import sys
import re
from copy import deepcopy
def parse(l):
groups = re.compile(r"(?P<p1>\w+)-(?P<p2>\w+)").search(l)
p1, p2 = groups.groups()
for p in (p1,p2):
if not p in opts.keys(): opts[p] = set()
if not p in opts.keys(): opts[p] = set()
if p.islower() and p not in ('start', 'end'): opts['small'].add(p)
if p.islower() and p not in ('start', 'end'): opts['small'].add(p)
opts[p1].add(p2)
opts[p2].add(p1)
def paths(p1, l, twice=''):
p = deepcopy(p1)
p.append(l)
if p.count(twice) > 1: twice = ''
if l == 'end':
pths.add(tuple(p))
return
for n in opts[l]:
if not ((n != twice and n in p and n in opts['small']) or n == 'start'):
paths(p, n, twice)
if __name__ == '__main__':
lines = open(sys.argv[1]).read().strip('\n\n').split('\n') # or split \n\n or sth similar
opts = {'start': set(), 'end': set(), 'small': set()}
[parse(i) for i in lines]
# challenge 1
pths = set()
paths([], 'start')
res1 = str(len(pths))
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
pths = set()
[paths([], 'start', t) for t in opts['small']]
res2 = str(len(pths))
print("challenge 2:" +"\n" + res2 + "\n")
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
import sys
def printi(dots):
st = ''
for y in range(max(dots,key=lambda x: x[1])[1]+1):
for x in range(max(dots,key=lambda x: x[0])[0]+1):
if (x,y) in dots: st += '#'
else: st += '.'
print(st)
st = ''
def fold(f, dots):
ndots, c = set(), f[1]
if f[0] == 'x': r = 0
elif f[0] == 'y': r = 1
for dot in dots:
if dot[r] < c: ndots.add(dot)
elif dot[r] > c: ndots.add([(c-(dot[0]-c),dot[1]), (dot[0],c-(dot[1]-c))][r])
return ndots
if __name__ == '__main__':
lines = open(sys.argv[1]).read().split('\n\n')
dots = set([tuple(map(int, line.split(','))) for line in lines[0].split('\n')])
folds = [i for i in map(lambda x: (x[0],int(x[1])), [tuple(line.strip('fold along ').split('=')) for line in lines[1].split('\n')[:-1]])]
# challenge 1
res1 = str(sum(1 for dot in fold(folds[0], dots)))
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
for f in folds: dots = fold(f,dots)
printi(dots)
res2 = "read yourself please xD"
print("challenge 2:" + "\n" + res2 + "\n")
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
import sys
from collections import Counter
from copy import deepcopy
def step(cons,s):
for _ in range(s):
ncons = {}
for (a,b),v in cons.items():
if (a, rules[a+b]) not in ncons: ncons[(a, rules[a+b])] = 0
if (rules[a+b], b) not in ncons: ncons[(rules[a+b], b)] = 0
ncons[(a, rules[a+b])] += v
ncons[(rules[a+b],b)] += v
cons = deepcopy(ncons)
return cons
def countp(cons):
ex = {}
for k in nex.keys():
ex[k[0]] = 0
ex[k[1]] = 0
ex[start[0]] += 1
ex[start[-1]] += 1
for k,v in nex.items():
ex[k[0]] += v
ex[k[1]] += v
return ex
if __name__ == '__main__':
start, rules = open(sys.argv[1]).read().split('\n\n')
rules = [r.split(' -> ') for r in rules.split('\n')]
rules = {a[0]:a[1] for a in rules[:-1]}
nex = {}
for a,b in zip(start[:-1],start[1:]):
if (a,b) not in nex: nex[(a,b)] = 0
nex[(a,b)] +=1
# challenge 1
nex = step(nex,10)
res = countp(nex)
res1 = str(max(res.values())//2-min(res.values())//2)
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
nex = step(nex,30)
res = countp(nex)
res2 = str(max(res.values())//2-min(res.values())//2)
print("challenge 2:" +"\n" + res2 + "\n")
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
import sys
def memo(f):
memo = {}
def f2(a,x,y,c,e):
if (x,y) not in memo: memo[(x,y)] = f(a,x,y,c,e)
return memo[(x,y)]
return f2
def nb(sx, sy):
n = [(0,1), (1,0), (0,-1), (-1,0)]
return [(max(0,sx+x), max(0,sy+y)) for x,y in n]
def dijkstra(graph, s):
a = {}
v = {}
Q = initG(graph, s, a, v)
lq = len(Q)
while len(Q) > 0:
u = min([u for u in Q], key=lambda x: a[x])
Q.remove(u)
for vo in nb(*u):
if vo in Q:
distance_update(graph, u,vo,a,v)
if (len(Q)/lq * 100 % 1) == 0:
print("|", end='', flush=True)
print("\n")
return v
def initG(graph, s, a, v):
for vo in graph.keys():
a[vo] = 9999999999999999
v[vo] = 'null'
a[s] = 0
Q = [n for n in graph.keys()]
return Q
def distance_update(g, u,vo,a,v):
alt = a[u] + g[u]
if alt < a[vo]:
a[vo] = alt
v[vo] = u
def shortest_path(g, d, v):
w = [d]
u = d
r = 0
while v[u] != 'null':
r += g[u]
u = v[u]
w.append(u)
return w.reverse(), r
if __name__ == '__main__':
nums = [[int(i) for i in list(line.strip('\n'))] for line in open(sys.argv[1])]
# challenge 1
g1 = {(x,y) : nums[y][x] for x in range(len(nums[0])) for y in range(len(nums))}
v = dijkstra(g1, (0,0))
w, r = shortest_path(g1, (len(nums)-1, len(nums[0])-1), v)
res1 = str(r)
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2 - inefficient
g2 = {(x+i*len(nums[0]),y+j*len(nums)) : (nums[y][x] + i + j if nums[y][x] + i + j < 10 else (nums[y][x] + i + j) % 10 + 1) for x in range(len(nums[0])) for y in range(len(nums)) for i in range(5) for j in range(5)}
v = dijkstra(g2, (0,0))
w, r = shortest_path(g2, (len(nums[0])*5-1, len(nums)*5-1), v)
res2 = str(r)
print("challenge 2:" +"\n" + res2 + "\n")
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
import sys
from bitstring import BitArray
from operator import mul
from functools import reduce
def parse_packet(packet, s, np=100000000, length=1000000000):
nex = s
end = s+length-1
bv = 0
numbers = []
while np > 0 and nex < min(len(packet)+1,end):
if (len(packet[nex:end+1]) == 0 or int(''.join(packet[nex:end+1]),2) == 0 or int(''.join(packet[nex:]),2) == 0):
if length < 1000000000: nex = end+1
break
v = int(''.join(packet[nex:nex+3]),2)
bv += v
t = int(''.join(packet[nex+3:nex+6]),2)
nex += 6
if t == 4:
num = []
while (n := packet[nex]) == '1':
num.append(list(packet[nex+1:nex+5]))
nex += 5
num.append(list(packet[nex+1:nex+5]))
nex += 5
i = int(''.join([''.join(n) for n in num]),2)
numbers.append(i)
else:
I = packet[nex]
nex += 1
if I == '1':
l = int(''.join(packet[nex:nex+11]),2)
nex += 11
b, nex, numbs = parse_packet(packet, nex, np=l)
bv += b
elif I == '0':
l = int(''.join(packet[nex:nex+15]),2)
nex += 15
b, nex, numbs = parse_packet(packet, nex, length=l)
bv += b
if t == 0: numbers.append(sum(numbs))
elif t == 1: numbers.append(reduce(mul, numbs, 1))
elif t == 2: numbers.append(min(numbs))
elif t == 3: numbers.append(max(numbs))
elif t == 5: numbers.append(int(numbs[0] > numbs[1]))
elif t == 6: numbers.append(int(numbs[0] < numbs[1]))
elif t == 7: numbers.append(int(numbs[0] == numbs[1]))
np -= 1
return bv, nex, numbers
if __name__ == '__main__':
hexa = [list(line.strip('\n')) for line in open(sys.argv[1])]
bits = [list(BitArray(hex=c).bin) for c in hexa[0]]
bits = [b for l in bits for b in l]
bv, _, num = parse_packet(bits,0,np=1)
# challenge 1
res1 = str(bv)
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
res2 = str(num[0])
print("challenge 2:" + "\n" + res2 + "\n")
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
import sys, re
def parse(l):
return re.compile(r"target area: x=(?P<x1>\d+)..(?P<x2>\d+), y=(?P<y1>-?\d+)..(?P<y2>-?\d+)").search(l)
def step(cx,cy,x,y):
cx += x
cy += y
x = x-1 if x > 0 else (x+1 if x < 0 else 0)
y -= 1
return cx,cy,x,y
def hits_target(x,y,t):
cx, cy, rt, my = 0,0, False, 0
while cx <= max(t[0]) and cy >= min(t[1]):
cx,cy,x,y = step(cx,cy,x,y)
my = max(my,cy)
if (min(t[0]) <= cx <= max(t[0])) and (min(t[1]) <= cy <= max(t[1])): rt = True
return my, rt
if __name__ == '__main__':
x1,x2,y1,y2 = map(int,parse(open(sys.argv[1]).read()).groups())
target = ((x1,x2),(y1,y2))
dic = {}
for x in range(target[0][1]+1):
for y in range(min(target[1]),target[0][1]+max(map(abs,target[1]))):
my,rt = hits_target(x,y,target)
if rt: dic[(x,y)] = my
# challenge 1
res1 = str(max(dic.values()))
print("challenge 1:" +"\n" + res1 + "\n")
# challenge 2
res2 = str(len(dic))
print("challenge 2:" +"\n" + res2 + "\n")
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
import sys, math
from functools import reduce
from copy import deepcopy
def magn(n):
if type(n) == int: return n
return 3*magn(n[0]) + 2*magn(n[1])
def explode(osn):
sn = deepcopy(osn)
l = None
r = 0
d = False
for i,n1 in enumerate(sn):
if type(n1) == int:
l = (0,i,n1)
if r != 0:
sn[i] = n1 + r
return sn
else:
for j,n2 in enumerate(n1):
if type(n2) == int:
l = (1,[i,j],n2)
if r != 0:
n1[j] = n2 + r
return sn
else:
for k,n3 in enumerate(n2):
if type(n3) == int:
l = (2,[i,j,k],n3)
if r != 0:
n2[k] = n3 + r
return sn
else:
for m,n4 in enumerate(n3):
if type(n4) == int:
l = (3,[i,j,k,m],n4)
if r != 0:
n3[m] = n4 + r
return sn
elif not d:
d = True
r = n4[1]
if l != None:
if l[0] == 0: sn[l[1]] = l[2] + n4[0]
elif l[0] == 1: sn[l[1][0]][l[1][1]] = l[2] + n4[0]
elif l[0] == 2: sn[l[1][0]][l[1][1]][l[1][2]] = l[2] + n4[0]
elif l[0] == 3: sn[l[1][0]][l[1][1]][l[1][2]][l[1][3]] = l[2] + n4[0]
n3[m] = 0
else:
if type(n4[0]) != int:
print('help!')
n4[0] += r
return sn
return sn
def split(osn):
sn = deepcopy(osn)
if isinstance(sn,list):
for i,n in enumerate(sn):
o = sn[i]
sn[i] = split(n)
if sn[i] != o: return sn
elif sn > 9:
return [math.floor(sn/2),math.ceil(sn/2)]
return sn
def snreduce(sn):
new = 0
old = sn
while old != new:
old = new if new != 0 else old
new = explode(old)
if new != old:
continue
new = split(old)
return new
def snadd(sn1,sn2):
sn = [sn1,sn2]
return snreduce(sn)
if __name__ == '__main__':
nums = [eval(line.strip('\n')) for line in open(sys.argv[1])]
# challenge 1
res1 = str(magn(reduce(snadd,nums)))
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
mm = 0
for n in nums:
for m in nums:
mm = max(mm, magn(snadd(n,m)))
res2 = str(mm)
print("challenge 2:" + "\n" + res2 + "\n")
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
import sys, math
import numpy as np
def rotations(x,y,z):
r = [
# x is facing x
[x, y, z],
[x, -z, y],
[x, -y, -z],
[x, z, -y],
# x is facing -x
[-x, -y, z],
[-x, -z, -y],
[-x, y, -z],
[-x, z, y],
# x is facing y
[-z, x, -y],
[y, x, -z],
[z, x, y],
[-y, x, z],
# x is facing -y
[z, -x, -y],
[y, -x, z],
[-z, -x, y],
[-y, -x, -z],
# x is facing z
[-y, -z, x],
[z, -y, x],
[y, z, x],
[-z, y, x],
# x is facing -z
[z, y, -x],
[-y, z, -x],
[-z, -y, -x],
[y, -z, -x]
]
for point in r:
yield np.array(point)
def overlap(s1,s2,off):
se1 = set([tuple(p) for p in s1])
se2 = set([tuple(p-off) for p in s2])
return len(se1.intersection(se2))
def test(s1,s2):
rot = [[r for r in rotations(*p)] for p in s2]
rot2 = [[r[i] for r in rot] for i in range(24)]
mc = 0
for i in range(24):
for p1 in s1:
for p2 in rot2[i]:
dif = p2 - p1
com = overlap(s1,rot2[i],dif)
if com > mc:
mc = com
if mc >= 12:
return [r - dif for r in rot2[i]], dif
return None, None
if __name__ == '__main__':
nums = [[np.array([i for i in map(int,n.split(','))]) for n in line.split('\n')[1:] if n != ''] for line in open(sys.argv[1]).read().split('\n\n')]
scanners = []
matched = {}
matched[0] = nums[0]
al = set([tuple(i) for i in matched[0]])
while len(matched) != len(nums):
for i in range(len(nums)):
if i in matched: continue
r = None
r, d = test(al,nums[i])
scanners.append(d)
if r != None:
matched[i] = r
al = al.union(set([tuple(i) for i in matched[i]]))
break
m = 0
for a in scanners:
for b in scanners:
n = sum(abs(a[i] - b[i]) for i in range(3))
if n > m:
m = n
# challenge 1
res1 = str(len(al))
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
res2 = str(m)
print("challenge 2:" + "\n" + res2 + "\n")
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
import sys
from copy import deepcopy
def imagine(im):
for y in im:
l = ''
for x in y: l += x
print(l)
def n(im,x,y,o):
index = ''
h = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,0), (0,1), (1,-1), (1,0), (1,1)]
for j,i in h:
if (0 <= x+i < len(im[0]) and 0 <= y+j < len(im)): index += '0' if im[y+j][x+i] == '.' else '1'
else: index += '0' if o == '.' else '1'
return algo[int(index,2)]
def enhance(im, o):
nex = deepcopy(im)
for y in range(len(im)):
for x in range(len(im[0])):
nex[y][x] = n(im,x,y,o)
return nex, '.' if o == '#' or mode == 'k' else '#'
if __name__ == '__main__':
algo, im = open(sys.argv[1]).read().split('\n\n')
algo = list(algo.strip('\n'))
im = [list(i) for i in im.split('\n') if i != '']
print('------------------ start -------------------')
bim = [[im[i-50][j-50] if (49 < i <= len(im)+49 and 49 < j <= len(im[0])+49) else '.' for j in range(len(im[0]) + 100)] for i in range(len(im) + 100)]
imagine(bim)
mode = 's' if algo[0] == '#' else 'k'
nim, o = bim, '.'
for i in range(50):
print('-------------------- ' + str(i) + ' ---------------------')
nim, o = enhance(nim,o)
imagine(nim)
if i == 1: c1 = nim
# challenge 1
res1 = str(sum(sum(1 if i == '#' else 0 for i in j) for j in c1))
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
res2 = str(sum(sum(1 if i == '#' else 0 for i in j) for j in nim))
print("challenge 2:" + "\n" + res2 + "\n")
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
import sys, re
def memo(fc):
memo = {}
def f2(a,b,c,d,e,f,g):
if (a,b,c,d,e,f,g) not in memo: memo[(a,b,c,d,e,f,g)] = fc(a,b,c,d,e,f,g)
return memo[(a,b,c,d,e,f,g)]
return f2
def parse(line):
groups = re.compile(r"Player 1 starting position: (?P<p1>\d+)\nPlayer 2 starting position: (?P<p2>\d+)").search(line)
return groups
def step(p1,p2):
d,s1,s2,die,dr = 0,0,0,0,0
t = 1
while s1 < 1000 and s2 < 1000:
mv = d*3 + 6
d = d + 3 % 100
dr += 3
if t == 1:
p1 = (p1 + mv - 1) % 10 + 1
s1 += p1
if t == 2:
p2 = (p2 + mv - 1) % 10 + 1
s2 += p2
t = t%2+1
return dr*s2 if s2 < 1000 else dr*s1
@memo
def qstep(p1,p2,s1,s2,dv,t,dt):
if s1 >= 21:
return {1:1,2:0}
elif s2 >= 21:
return {1:0,2:1}
wins = {1: 0, 2: 0}
if t == 1:
if dt == 3:
nt = t%2+1
np1 = (p1 + dv - 1) % 10 + 1
ns1 = s1+np1
win = qstep(np1,p2,ns1,s2,0,nt,0)
wins[1] += win[1]
wins[2] += win[2]
else:
dt += 1
for d in range(1,4):
ndv = dv+d
win = qstep(p1,p2,s1,s2,ndv,t,dt)
wins[1] += win[1]
wins[2] += win[2]
if t == 2:
if dt == 3:
nt = t%2+1
np2 = (p2 + dv - 1) % 10 + 1
ns2 = s2+np2
win = qstep(p1,np2,s1,ns2,0,nt,0)
wins[1] += win[1]
wins[2] += win[2]
else:
dt += 1
for d in range(1,4):
ndv = dv+d
win = qstep(p1,p2,s1,s2,ndv,t,dt)
wins[1] += win[1]
wins[2] += win[2]
return wins
if __name__ == '__main__':
p1,p2 = map(int,parse(open(sys.argv[1]).read()).groups())
# challenge 1
res1 = str(step(p1,p2))
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
results = qstep(p1,p2,0,0,0,1,0)
res2 = str(max(results.values()))
print("challenge 2:" + "\n" + res2 + "\n")
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
import sys,re
from collections import Counter
def parse(l):
return re.compile(r"(?P<mode>\w+) x=(?P<x1>-?\d+)..(?P<x2>-?\d+),y=(?P<y1>-?\d+)..(?P<y2>-?\d+),z=(?P<z1>-?\d+)..(?P<z2>-?\d+)").search(l)
def volume(k):
if k[1]-k[0] < 0 or k[3]-k[2] < 0 or k[5]-k[4] < 0: return 0
return (k[1]-k[0]+1)*(k[3]-k[2]+1)*(k[5]-k[4]+1)
def count_cubes(c):
o = 0
for k,v in c.items():
if v == 'on':
o += volume(k)
return o
def intersect(c1,c2):
x1,x2,y1,y2,z1,z2 = c1
lx,hx,ly,hy,lz,hz = c2
xos = max(lx,x1)
xoe = min(hx,x2)
yos = max(ly,y1)
yoe = min(hy,y2)
zos = max(lz,z1)
zoe = min(hz,z2)
return volume((xos,xoe,yos,yoe,zos,zoe)) > 0
#return (c1[0] in range(c2[0],c2[1]+1) or c1[1] in range(c2[0],c2[1]+1)) and (c1[2] in range(c2[2],c2[3]+1) or c1[3] in range(c2[2],c2[3]+1)) and (c1[4] in range(c2[4],c2[5]+1) or c1[5] in range(c2[4],c2[5]+1))
def split(c1,c2):
x1,x2,y1,y2,z1,z2 = c1
lx,hx,ly,hy,lz,hz = c2
xos = max(lx,x1)
xoe = min(hx,x2)
yos = max(ly,y1)
yoe = min(hy,y2)
zos = max(lz,z1)
zoe = min(hz,z2)
v = 0
for x in [(lx,xos-1),(xos,xoe),(xoe+1,hx)]:
for y in [(ly,yos-1),(yos,yoe),(yoe+1,hy)]:
for z in [(lz,zos-1),(zos,zoe),(zoe+1,hz)]:
v += volume((*x,*y,*z))
if volume((*x,*y,*z)) > 0 and (x,y,z) != ((xos,xoe),(yos,yoe),(zos,zoe)):
yield (*x,*y,*z)
def init(steps):
cubes = {}
for m,x1,x2,y1,y2,z1,z2 in steps:
if not (-50 <= x1 <= 50 and -50 <= x2 <= 50): continue
for x in range(x1,x2+1):
if not (-50 <= y1 <= 50 and -50 <= y2 <= 50): continue
for y in range(y1,y2+1):
if not (-50 <= z1 <= 50 and -50 <= z2 <= 50): continue
for z in range(z1,z2+1):
cubes[(x,y,z)] = m
return cubes
def reboot(steps):
cubes = {}
for c1 in steps:
m,c1 = c1[0],c1[1:]
atm = [k for k in cubes.keys()]
for c2 in atm:
om = cubes[c2]
if intersect(c1,c2) or intersect(c2,c1):
for c in split(c1,c2):
if not (intersect(c,c1) or intersect(c1,c)):
cubes[c] = om
cubes.pop(c2)
cubes[c1] = m
return cubes
if __name__ == '__main__':
nums = map(lambda x: (x[0],int(x[1]),int(x[2]),int(x[3]),int(x[4]),int(x[5]),int(x[6])),[parse(l).groups() for l in open(sys.argv[1])])
nums = [n for n in nums]
# challenge 1
cubes1 = init(nums)
c = Counter([v for k,v in cubes1.items() if -50 <= k[0] <= 50 and -50 <= k[1] <= 50 and -50 <= k[2] <= 50])
res1 = str(c.most_common(2))
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
cubes2 = reboot(nums)
res2 = str(count_cubes(cubes2))
print("challenge 2:" + "\n" + res2 + "\n")
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
import sys
from functools import cache
@cache
def path(f1,f2):
path = []
y, x = f1
while y != 0:
y -= 1
path.append((y,x))
while x != f2[1]:
x += 1 if f2[1] > x else -1
path.append((y,x))
while y != f2[0]:
y += 1
path.append((y,x))
assert path[-1] == f2
return path
def pathvalid(path,board):
for p in path:
if p in board: return False
return True
def cost(a,w):
if a == 'A': return len(w) * 1
if a == 'B': return len(w) * 10
if a == 'C': return len(w) * 100
if a == 'D': return len(w) * 1000
def endstate(board):
for f,a in board.items():
if f[1] != target[a]: return False
return True
def target_position(f,b,lowest):
a = b[f]
if f[1] != target[a]: return False
for y in range(f[0],lowest+1):
if (y,target[a]) not in b: return False
if b[(y,target[a])] != a: return False
return True
def totarget(board,lowest):
change = False
costs = 0
nb = {k: v for k,v in board.items()}
for f,a in board.items():
if target_position(f,nb,lowest): continue
t = (lowest,target[a])
while t in nb and nb[t] == a:
t = (t[0]-1,target[a])
if t == (0,target[a]): continue
p = path(f,t)
if pathvalid(p,nb):
change = True
nb.pop(f)
nb[t] = a
costs += cost(a,p)
return nb,costs,change
def dfs(board,lowest,costs=0,curmin=sys.maxsize):
ch = True
nb = {k: v for k,v in board.items()}
while ch:
nb,co,ch = totarget(nb,lowest)
costs += co
if endstate(nb):
return costs
if costs > curmin: return None
board = {k: v for k,v in nb.items()}
for f,a in board.items():
if f[0] != 0 and not(target_position(f,board,lowest)):
for f2 in hallway:
p = path(f,f2)
if pathvalid(p, board):
cb = {k: v for k,v in board.items()}
cb.pop(f)
cb[f2] = a
nc = dfs(cb,lowest,costs+cost(a,p),curmin)
if nc is not None and nc < curmin: curmin = nc
if curmin < sys.maxsize: return curmin
if __name__ == '__main__':
# challenge 1
lines = open(sys.argv[1]).readlines()
start = {}
for y,l in enumerate(lines[1:]):
for x,f in enumerate(l[1:]):
if f in 'ABCD': start[(y,x)] = f
hallway = [(0,0), (0,1), (0,3), (0,5), (0,7), (0,9), (0,10)]
target = {'A': 2, 'B': 4, 'C': 6, 'D': 8}
res1 = str(dfs(start,2))
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
lines = open(sys.argv[2]).readlines()
start = {}
for y,l in enumerate(lines[1:]):
for x,f in enumerate(l[1:]):
if f in 'ABCD': start[(y,x)] = f
res2 = str(dfs(start,4))
print("challenge 2:" + "\n" + res2 + "\n")
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
import sys, re, math
from operator import add, mul, truediv, mod
from functools import reduce
def parse(line):
l = line.split(' ')
if l[0] == 'inp': i,o = l
else: i,o = l[0], [l[1],l[2]]
return (i,o)
def replist(l,v,r):
return [r if i == v else i for i in l]
def eql(a,b):
return int(a == b)
def div(a,b):
return math.trunc(reduce(truediv,[a,b]))
def alu(instruction, inp):
reg = {'w': 0, 'x': 0, 'y': 0, 'z': 0}
inp = list(str(inp))
index = 0
for i,ops in instruction:
if i == 'inp':
reg[ops] = inp[index]
index += 1
else:
reg[ops[0]] = reduce(eval(i),[int(reg[o]) if o in 'wxyz' else int(o) for o in ops])
return reg
if __name__ == '__main__':
instr = [parse(line.strip('\n')) for line in open(sys.argv[1])]
for i in range(1,9):
for k in range(11111111111,99999999999):
for j in ['18','27']:
r = alu(instr,str(i)+j+str(k))
print(str(i)+j+str(k),r)
if r['z'] == 0: print(i,j,k)
for i in range(99999999999999,9999999999999,-1):
if i % 10000 == 0: print(i)
if '0' in str(i): continue
r = alu(instr,str(i))
if r['z'] == 0:
print(i)
break
# challenge 1
res1 = ""
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
res2 = ""
print("challenge 2:" + "\n" + res2 + "\n")
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
import sys
from copy import deepcopy
def cprint(cucs):
for l in cucs:
print(''.join(l))
print('\n')
def step(cucs):
nc = deepcopy(cucs)
for y,l in enumerate(cucs):
for x,c in enumerate(l):
if c == '>':
if cucs[y][(x+1)%len(l)] == '.':
nc[y][x] = '.'
nc[y][(x+1)%len(l)] = '>'
cucs = deepcopy(nc)
for y,l in enumerate(cucs):
for x,c in enumerate(l):
if c == 'v':
if cucs[(y+1)%len(cucs)][x] == '.':
nc[y][x] = '.'
nc[(y+1)%len(cucs)][x] = 'v'
return nc
if __name__ == '__main__':
cucs = [list(line.strip('\n')) for line in open(sys.argv[1])]
# challenge 1
nc = []
i = 0
while nc != cucs:
print(i)
i += 1
cprint(nc)
cucs = deepcopy(nc) if nc != [] else cucs
nc = step(cucs)
res1 = str(i)
print("challenge 1:" + "\n" + res1 + "\n")
# challenge 2
res2 = "doesn't exist :)"
print("challenge 2:" + "\n" + res2 + "\n")
+109
View File
@@ -0,0 +1,109 @@
:- use_module(library(clpfd)).
% den state kannst du mit nem dictoniary modellieren:
initState(state{ x: 0, y: 0, z:0, w: 0 , in: I}, I).
% Dictonary lookup: initstate(State), R = State.x
% Dictonary update: initstate(State), NewState = State.put(x, 1)
% Convert List of input digits into single number
%input_number(+Inputs, -Number)
input_number(Inputs, Number) :- atomic_list_concat(Inputs, Number).
% read program helper functions
noteof(L) :- \+ L = [end_of_file].
string_term(String,Term) :- term_string(Term, String).
parse_instr(String, Inst) :-
split_string(String, " ", "", Words),
maplist(string_term, Words, Inst).
% Read a list of Instructions from Filename
% read_program(+Filename, -Prog)
read_program(Filename, Prog) :-
open(Filename, read, Str),
read_string(Str, _, S),
split_string(S, "\n", "", Lines),
maplist(parse_instr, Lines, Instrs),
include(noteof, Instrs, Prog),
close(Str).
% Takes input and state and binds O to a number
num(N,S,O) :-
atom(N),
O = S.N.
num(N,S,O) :-
number(N),
O = N.
eq(A,B,R) :-
A = B,
R = 1.
eq(A,B,R) :-
A #\= B,
R = 0.
read_input(In,F,NIn) :-
[F | NIn] = In.
% interprets an instruction
% interpret(+list,+state,R)
interpret([inp, A],InState,OutState) :-
read_input(InState.in,C,NInput),
BS = InState.put(A,C),
OutState = BS.put(in,NInput).
interpret([add, A, B],InState,OutState) :-
num(B,InState,C),
R #= InState.A + C,
OutState = InState.put(A,R).
interpret([mul, A, B],InState,OutState) :-
num(B,InState,C),
R #= InState.A*C,
OutState = InState.put(A,R).
interpret([div, A, B],InState,OutState) :-
num(B,InState,C),
R #= InState.A div C,
OutState = InState.put(A,R).
interpret([mod, A, B],InState,OutState) :-
num(B,InState,C),
R #= InState.A mod C,
OutState = InState.put(A,R).
interpret([eql, A, B],InState,OutState) :-
num(B,InState,C),
eq(InState.A, C, R),
OutState = InState.put(A,R).
rprogram(State,[],O) :-
O = State.z.
rprogram(State,[I|Instr], O) :-
interpret(I,State,Out),
rprogram(Out,Instr,O).
program(Instr,Input) :-
length(Input, 14),
Input ins 1..9,
initState(S,Input),
rprogram(S,Instr, O),
O = 0.
max_monad(M) :-
read_program(input24,Instr),
program(Instr,R),
labeling([max,down],R),
input_number(R,M),
write(M).
min_monad(M) :-
read_program(input24,Instr),
program(Instr,R),
labeling([min],R),
input_number(R,M),
write(M).