change structure of folders

This commit is contained in:
Maya Herrscher committed 2021-11-30 00:18:33 +01:00
1 parent 61ab2df755
commit c10382b0c0
20 files changed

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
import sys
import re
def parse_rules(lines):
rules = {}
for line in lines:
rule, pattern = line.split(':')
alternatives = pattern.split('|')
rules[int(rule)] = [a.strip(' ').split(' ') for a in alternatives]
return rules
def memo(f):
mem = {}
def helper(x):
if x not in mem: mem[x] = f(x)
return mem[x]
return helper
@memo
def expr(rule):
if rule == 8:
return expr(42) + '+'
if rule == 11:
return '(?:' + expr(42) + '(?=a*(\1?+b)b*(\2?+c)))+\1' + expr(31) + ')'
global rules
if type(rule) is str:
try: rule = int(rule)
except ValueError: return rule[1]
pattern = rules[rule]
res = ["".join(expr(dep) for dep in alt) for alt in pattern]
if len(res) == 1: return res[0]
return "(" + "|".join(res) + ")"
if __name__ == '__main__':
rules, messages = open(sys.argv[1]).read().split('\n\n')
rules = parse_rules(rules.split('\n'))
count = 0
messages = messages.split("\n")
for m in messages:
if bool(re.match('^' + expr(0) + '$', m)):
count += 1
print(count)
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
import sys
from termcolor import colored
def show(tile):
for line in tile:
print(colored(''.join(line), 'blue'))
print('\n')
def fliph(tile):
next = ['n'] * 10
for i in range(0,len(tile)):
next[i] = tile[len(tile)-i-1]
return next
def flipv(tile):
for i in range(0, len(tile)):
tile[i] = tile[i][::-1]
return tile
def rotate(tile):
next = [['o' for i in range(len(tile[0]))] for j in range(len(tile))]
for i in range(0, len(tile)):
for j in range(0, len(tile[1])):
next[len(tile[1])-j-1][i] = tile[i][j]
return next
def options(tile):
return [tile,
fliph(tiles[t]),
rotate(tiles[t]),
rotate(rotate(tiles[t])),
rotate(rotate(rotate(tiles[t]))),
fliph(rotate(tiles[t])),
fliph(rotate(rotate(tiles[t]))),
fliph(rotate(rotate(rotate(tiles[t]))))]
if __name__ == '__main__':
tilestrings = open(sys.argv[1]).read().split('\n\n')
tiles = {}
for tile in tilestrings:
tid, *data = tile.split('\n')
try:
tid = tid.rstrip(':').split(' ')[1]
except IndexError: continue
grid = [[c for c in line] for line in data if len(line) >= 1]
tiles[int(tid)] = grid
for t in tiles:
print(colored(str(t), 'red'))
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
import sys
import numpy as np
def toBits(l): return sum(int(b=='#') * (2**i) for i,b in enumerate(l))
def allSides(tile):
a,b,c,d = tile[0, : ], tile[-1, : ], tile[:, 0], tile[:, -1]
e,f,g,h = tile[0, ::-1], tile[-1, ::-1], tile[::-1, 0], tile[::-1, -1]
return [a,b,c,d,e,f,g,h]
def comb(tile):
return [tile,
np.fliplr(tile),
np.rot90(tile),
np.rot90(np.rot90(tile)),
np.rot90(np.rot90(np.rot90(tile))),
np.fliplr(np.rot90(tile)),
np.fliplr(np.rot90(np.rot90(tile))),
np.fliplr(np.rot90(np.rot90(np.rot90(tile))))]
def getRight(tile): return toBits(tile[:,-1])
def getLeft(tile): return toBits(tile[:,0])
def getBot(tile): return toBits(tile[-1,:])
def getTop(tile): return toBits(tile[0,:])
def matchRight(tile1, tile2):
for t in comb(tile2):
if getRight(tile1) == getLeft(t):
return t
def matchBot(tile1, tile2):
for t in comb(tile2):
if getBot(tile1) == getTop(t):
return t
if __name__ == '__main__':
tilestrings = open(sys.argv[1]).read().split('\n\n')
tiles = {}
for tile in tilestrings:
tid, *data = tile.split('\n')
try:
tid = tid.rstrip(':').split(' ')[1]
except IndexError: continue
grid = [[c for c in line] for line in data if len(line) >= 1]
tiles[int(tid)] = np.array(grid)
sides = {}
for tid, tile in tiles.items():
for x in allSides(tile):
bits = toBits(x)
if bits not in sides: sides[bits] = []
sides[bits].append(tid)
sides = {k:v for k,v in sorted(sides.items(), key=lambda i: len(i[1]))}
singles = {}
for bits, xs in sides.items():
if len(xs) == 1:
singles[xs[0]] = []
for sid in singles.keys():
matches = [x for side in allSides(tiles[sid]) for x in sides[toBits(side)]]
singles[sid] = list(dict.fromkeys(matches))
prod = 1
corner = None
for sid, single in singles.items():
if len(single) < 4:
prod *= sid
corner = sid
picture = [[None for x in range(12)] for x in range(12)]
matches = list(dict.fromkeys([x for side in allSides(tiles[corner]) for x in sides[toBits(side)]]))
matches.remove(corner)
for t in comb(tiles[corner]):
x, y = matches
x, y = tiles[x], tiles[y]
if matchRight(t,x) is not None and matchBot(t,y) is not None:
tiles[corner] = t
break
if matchRight(t,y) is not None and matchBot(t,x) is not None:
tiles[corner] = t
break
picture[0][0] = corner
for i, p in enumerate(picture[0]):
s = sides[getRight(tiles[p])]
s.remove(p)
if len(s) > 0:
tiles[s[0]] = matchRight(tiles[p], tiles[s[0]])
picture[0][i+1] = s[0]
for j in range(1, len(picture)):
z = sides[getBot(tiles[p])]
z.remove(p)
if len(z) > 0:
tiles[z[0]] = matchBot(tiles[p], tiles[z[0]])
picture[j][i] = z[0]
p = z[0]
print(picture)
pic = [[None for x in range(12)] for x in range(12)]
for i in range(len(picture)):
for j in range(len(picture[0])):
pic[i][j] = tiles[picture[i][j]]
print(pic)
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
import sys
import numpy as np
#import matplotlib.pyplot as plt
def toBits(l): return sum(int(b=='#') * (2**i) for i,b in enumerate(l))
def allSides(tile):
a,b,c,d = tile[0, : ], tile[-1, : ], tile[:, 0], tile[:, -1]
e,f,g,h = tile[0, ::-1], tile[-1, ::-1], tile[::-1, 0], tile[::-1, -1]
return [a,b,c,d,e,f,g,h]
def comb(tile):
return [tile,
np.fliplr(tile),
np.rot90(tile),
np.rot90(np.rot90(tile)),
np.rot90(np.rot90(np.rot90(tile))),
np.fliplr(np.rot90(tile)),
np.fliplr(np.rot90(np.rot90(tile))),
np.fliplr(np.rot90(np.rot90(np.rot90(tile))))]
def getRight(tile): return toBits(tile[:,-1])
def getLeft(tile): return toBits(tile[:,0])
def getBot(tile): return toBits(tile[-1,:])
def getTop(tile): return toBits(tile[0,:])
def matchRight(tile1, tile2):
for t in comb(tile2):
if getRight(tile1) == getLeft(t): return t
def matchBot(tile1, tile2):
for t in comb(tile2):
if getBot(tile1) == getTop(t): return t
def parse_data(strings):
tiles = {}
for tile in strings:
tid, *data = tile.split('\n')
try: tid = tid.rstrip(':').split(' ')[1]
except IndexError: continue
grid = [[c for c in line] for line in data if len(line) >= 1]
tiles[int(tid)] = np.array(grid)
return tiles
def get_sides(tiles):
sides = {}
for tid, tile in tiles.items():
for bits in map(lambda x: toBits(x), allSides(tile)):
if bits not in sides: sides[bits] = []
sides[bits].append(tid)
return sides
def get_corners(tiles, sides):
singles = {}
for bits, xs in sides.items():
if len(xs) == 1: singles[xs[0]] = []
for sid in singles.keys():
matches = [x for side in allSides(tiles[sid]) for x in sides[toBits(side)]]
singles[sid] = list(dict.fromkeys(matches))
corners = []
for sid, single in singles.items():
if len(single) < 4: corners.append(sid)
return corners
def build_picture(tiles, sides, start):
picture = [[None for x in range(12)] for x in range(12)]
matches = [x for side in allSides(tiles[corner]) for x in sides[toBits(side)]]
matches = list(dict.fromkeys(matches))
matches.remove(corner)
for t in comb(tiles[corner]):
x, y = map(lambda v: tiles[v], matches)
if matchRight(t,x) is not None and matchBot(t,y) is not None: break
if matchRight(t,y) is not None and matchBot(t,x) is not None: break
else: tiles[corner] = t
picture[0][0] = corner
for i, p in enumerate(picture[0]):
s = sides[getRight(tiles[p])]
s.remove(p)
if len(s) > 0:
tiles[s[0]] = matchRight(tiles[p], tiles[s[0]])
picture[0][i+1] = s[0]
for j in range(1, len(picture)):
z = sides[getBot(tiles[p])]
z.remove(p)
if len(z) > 0:
tiles[z[0]] = matchBot(tiles[p], tiles[z[0]])
picture[j][i] = z[0]
p = z[0]
return picture
def countSM(pic, sm):
count = 0
y, x = pic.shape
ys, xs = sm.shape
for i in range(0, y-ys):
for j in range(0, x-xs):
if np.all(pic[i:i+ys,j:j+xs] | sm):
count += 1
return count
if __name__ == '__main__':
tiles = parse_data(open(sys.argv[1]).read().split('\n\n'))
sides = get_sides(tiles)
corner = get_corners(tiles, sides)[0]
p = build_picture(tiles, sides, corner)
print(p[0][0] * p[0][-1] * p[-1][0] * p[-1][-1])
pic = np.concatenate(tuple(np.concatenate(tuple(tiles[x][1:-1,1:-1] for x in r), axis=1) for r in p), axis=0)
grayscale = np.vectorize(lambda x: np.int8(x == "#"))(pic)
print(grayscale)
snake = \
[ " # "
, "# ## ## ###"
, " # # # # # # "
]
sneasnake = np.array([[c for c in line] for line in snake])
sneasnake = np.vectorize(lambda x: np.int8(x != "#"))(sneasnake)
for p in comb(grayscale):
print(countSM(p, sneasnake))
print(np.count_nonzero(grayscale) - 26 * 15)
# plt.show()
# plt.imshow(grayscale)
# plt.savefig("test.png")
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
import sys
def parse(line):
line = line.split('(')
line[0] = line[0].split(' ')[:-1]
line[1] = line[1][9:-2]
line[1] = line[1].split(', ')
return line
if __name__ == '__main__':
ingr = open(sys.argv[1]).readlines()
ingredients = [parse(i) for i in ingr]
allergenes = []
for i in ingredients:
for a in i[1]:
allergenes.append(a)
allergenes = set(allergenes)
dicta = {}
for i in ingredients:
for a in i[1]:
if a not in dicta:
dicta[a] = [x for x in i[0]]
else:
copy = [x for x in dicta[a]]
for w in copy:
if w not in i[0]:
dicta[a].remove(w)
count = 0
for i in ingredients:
for n in i[0]:
b = True
for v in dicta.values():
if n in v:
b = False
if b:
count += 1
print(count)
dicta = {k:v for k,v in sorted(dicta.items(),key = lambda i: i[0])}
for w in range(len(dicta)):
for a, i in dicta.items():
if len(i) == 1:
for b, j in dicta.items():
if b != a and i[0] in j:
j.remove(i[0])
for k, v in dicta.items():
dicta[k] = v[0]
print(','.join(dicta.values()))
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
import sys
def step(deck1, deck2):
new1, new2 = [x for x in deck1[1:]], [y for y in deck2[1:]]
if deck1[0] > deck2[0]:
new1.append(deck1[0])
new1.append(deck2[0])
else:
new2.append(deck2[0])
new2.append(deck1[0])
return new1, new2
def game(deck1, deck2):
while len(deck1) > 0 and len(deck2) > 0:
deck1, deck2 = step(deck1, deck2)
if len(deck1) > 0: return "1", deck1
else: return "2", deck2
def recursive_game(deck1, deck2):
comb = []
while True:
if len(deck1) == 0: return 'player2', deck2
if len(deck2) == 0: return 'player1', deck1
new1, new2 = [x for x in deck1[1:]], [y for y in deck2[1:]]
if (deck1, deck2) in comb: return 'player1', deck1
comb.append((deck1, deck2))
if len(new1) >= deck1[0] and len(new2) >= deck2[0]:
if recursive_game(deck1[1:(deck1[0]+1)], deck2[1:(deck2[0]+1)])[0] == 'player1':
new1.append(deck1[0])
new1.append(deck2[0])
else:
new2.append(deck2[0])
new2.append(deck1[0])
deck1, deck2 = [x for x in new1], [y for y in new2]
else: deck1, deck2 = step(deck1, deck2)
def score(deck):
count = 0
for i, n in enumerate(deck):
count += ((len(deck)-i) * n)
return count
if __name__ == '__main__':
decks = open(sys.argv[1]).read()
deck1, deck2 = decks.split('\n\n')
deck1, deck2 = deck1.split('\n')[1:], deck2.split('\n')[1:-1]
deck1, deck2 = [int(i) for i in deck1], [int(j) for j in deck2]
rdeck1, rdeck2 = [x for x in deck1], [y for y in deck2]
winner, windeck = game(deck1, deck2)
print(winner, score(windeck))
winner, wdeck = recursive_game(rdeck1, rdeck2)
print(winner, score(wdeck))
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
from blist import blist
def destination(c, out):
while True:
if c-1>0 and c-1 not in out:
return c-1, order.index(c-1)
else:
if c>1:
c = c-1
else:
c = highest+1
def move(order):
rem = order
a = rem.pop(1)
b = rem.pop(1)
c = rem.pop(1)
_, dest = destination(order[0], [a,b,c])
rem.insert(dest+1, a)
rem.insert(dest+2, b)
rem.insert(dest+3, c)
if __name__ == "__main__":
#test_order = [3,8,9,1,2,5,4,6,7]
order = blist([1,9,8,7,5,3,4,6,2])
for x in range(10,1000001):
order.append(x)
current_index = 0
lowest = min(order)
highest = 1000000
#highest = max(order)
for i in range(10000000):
print(i)
move(order)
current_index += 1
last = order.pop(0)
order.append(last)
order = order[order.index(1):] + order[:order.index(1)]
print(order)
print(order[1]*order[2])
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
import sys
def destination(v, l): return (v - 2) % l + 1
def move(cycle, current):
a = cycle[current]
b = cycle[a]
c = cycle[b]
dest = destination(current, len(cycle))
if dest in [a,b,c]: dest = destination(dest, len(cycle))
if dest in [a,b,c]: dest = destination(dest, len(cycle))
if dest in [a,b,c]: dest = destination(dest, len(cycle))
cycle[current] = cycle[c]
cycle[c] = cycle[dest]
cycle[dest] = a
def score(cycle):
cups = []
current = 1
for _ in cycle:
current = cycle[current]
cups.append(current)
return "".join(str(cup) for cup in cups[:-1])
def solve(cups, num_moves):
# Current Cup is first cup in list
current = cups[0]
# Cycle[cup_value] = next_cup_value in clockwise order
cycle = {}
for i, cup in enumerate(cups):
cycle[int(cup)] = cups[(i + 1) % len(cups)]
for _ in range(num_moves):
move(cycle, current)
current = cycle[current]
return cycle
if __name__ == '__main__':
cups = [int(i) for i in list(sys.argv[1])]
print(score(solve(cups, 100)))
million = 1000000
new_cups = cups + [x for x in range(10, million+1)]
cycle = solve(new_cups, 10*million)
a = cycle[1]
b = cycle[a]
print(a*b)
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
import sys
def neighbors(x,y,z):
r = []
try: r.append(floor[x+1,y-1,z])
except KeyError: pass
try: r.append(floor[x-1,y+1,z])
except KeyError: pass
try: r.append(floor[x+1,y,z-1])
except KeyError: pass
try: r.append(floor[x-1,y,z+1])
except KeyError: pass
try: r.append(floor[x,y-1,z+1])
except KeyError: pass
try: r.append(floor[x,y+1,z-1])
except KeyError: pass
return r
def day(floor):
copy = {}
for (x,y,z) in floor:
copy[(x,y,z)] = floor[(x,y,z)]
c = sum([i%2 for i in neighbors(x,y,z)])
if floor[(x,y,z)] % 2 == 1 and (c == 0 or c > 2):
copy[(x,y,z)] += 1
if floor[(x,y,z)] % 2 == 0 and c == 2:
copy[(x,y,z)] += 1
return copy
if __name__ == '__main__':
lines = open(sys.argv[1]).readlines()
for i, line in enumerate(lines):
lines[i] = list(line[:-1])
for line in lines:
for j, b in enumerate(line):
if b == 'n' or b == 's':
line[j] = line[j] + line.pop(j+1)
floor = {}
for x in range(-120, 121):
for y in range(-120,121):
z = -(x+y)
floor[(x,y,z)] = 0
for line in lines:
x, y, z = 0, 0, 0
for d in line:
if d == 'e':
x += 1
y -= 1
if d == 'w':
x -= 1
y += 1
if d == 'ne':
x += 1
z -= 1
if d == 'nw':
y += 1
z -= 1
if d == 'se':
y -= 1
z += 1
if d == 'sw':
x -= 1
z += 1
if (x,y,z) in floor:
floor[(x,y,z)] += 1
else:
floor[(x,y,z)] = 1
count = 0
for a in floor.values():
if a%2 == 1:
count += 1
print(count)
for _ in range(100):
floor = day(floor)
count = 0
for a in floor.values():
if a%2 == 1:
count += 1
print(count)
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
import sys
if __name__ == '__main__':
lines = open(sys.argv[1]).readlines()
for i, line in enumerate(lines):
lines[i] = list(line[:-1])
for line in lines:
for j, b in enumerate(line):
if b == 'n' or b == 's':
line[j] = line[j] + line.pop(j+1)
for a, line in enumerate(lines):
for i in range(len(line)):
for j in range(i+1, len(line)):
x, y = line[i], line[j]
if (x == 'e' and y == 'w') or (x == 'w' and y == 'e') or (x == 'se' and y == 'sw') or (x == 'sw' and y == 'se') or (x == 'ne' and y == 'nw') or (x == 'nw' and y == 'ne'):
line[j] = ''
line[i] = ''
line.sort()
lines[a] = ''.join(line)
dict = {}
for di in lines:
if di in dict:
dict[di] += 1
else:
dict[di] = 1
count = 0
for a in dict.values():
if a % 2 == 1:
count += 1
print(count)
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
import sys
if __name__ == '__main__':
key1, key2 = open(sys.argv[1]).readlines()
print(key1, key2)
key1, key2 = int(key1), int(key2)
v = 1
ls1 = 0
while v != key1:
v = (v*7) % 20201227
ls1 += 1
print(ls1)
v = 1
ls2 = 0
while v != key2:
v = (v*7) % 20201227
ls2 += 1
print(ls2)
ek2 = 1
for _ in range(ls1):
ek2 = (ek2*key2) % 20201227
ek1 = 1
for _ in range(ls2):
ek1 = (ek1*key1) % 20201227
print(ek1, ek2)