├── 2015 ├── 1 │ ├── p1.py │ └── p2.py └── 2 │ ├── p1.py │ └── p2.py ├── 2021 ├── 1 │ ├── p1.py │ └── p2.py ├── 2 │ ├── p1.py │ └── p2.py ├── 3 │ ├── p1.py │ └── p2.js ├── 4 │ ├── p1.py │ └── p2.py ├── 5 │ ├── p1.py │ └── p2.py ├── 6 │ ├── p1.py │ └── p2.py ├── 7 │ ├── p1.py │ └── p2.py ├── 9 │ ├── p1.py │ └── p2.py └── 10 │ ├── p1.py │ └── p2.py ├── 2022 ├── 1 │ ├── p1.pipe │ ├── p1.py │ ├── p2.pipe │ └── p2.py ├── 2 │ ├── p1.pipe │ ├── p1.py │ ├── p2.pipe │ └── p2.py ├── 3 │ ├── p1.pipe │ ├── p1.py │ ├── p2.pipe │ └── p2.py ├── 4 │ ├── p1.pipe │ ├── p1.py │ ├── p2.pipe │ └── p2.py ├── 5 │ ├── p1.pipes │ ├── p1.py │ └── p2.py ├── 6 │ ├── p1.pipes │ ├── p1.py │ ├── p2.pipes │ └── p2.py ├── 7 │ ├── p1.py │ ├── p2.py │ └── pf.py ├── 8 │ ├── p1.py │ └── p2.py ├── 9 │ ├── p1.py │ └── p2.py ├── 10 │ ├── p1.py │ └── p2.py ├── 11 │ ├── p1.py │ └── p2.py ├── 12 │ ├── p1.py │ └── p2.py ├── 13 │ ├── p1.py │ └── p2.py ├── 14 │ ├── p1.py │ └── p2.py ├── 15 │ ├── p1.py │ └── p2.py ├── 16 │ ├── p1.py │ └── p2.py ├── 17 │ ├── p1.py │ └── p2.py ├── 18 │ ├── p1.py │ ├── p2.py │ └── pr.py ├── 19 │ ├── p1.py │ └── p2.py ├── 20 │ ├── p1.py │ └── p2.py ├── 21 │ ├── p1.py │ └── p2.py ├── 22 │ ├── p1.py │ └── p2.py ├── 23 │ ├── p1.py │ └── p2.py ├── 24 │ ├── p1.py │ └── p2.py └── 25 │ └── p1.py ├── 2023 ├── 10 │ ├── p1.py │ └── p2.py ├── 11 │ ├── p1.py │ └── p2.py ├── 12 │ ├── p1.py │ └── p2.py ├── 14 │ ├── p1.py │ └── p2.py ├── 15 │ ├── p1.py │ └── p2.py ├── 16 │ ├── p1.py │ └── p2.py ├── 17 │ ├── p1.py │ └── p2.py ├── 18 │ └── p1.py ├── 19 │ └── p1.py ├── 23 │ └── p1.py ├── 24 │ ├── p1.py │ └── p2.py ├── 25 │ └── p1.py ├── 01 │ ├── p1.py │ └── p2.py ├── 02 │ ├── p1.py │ └── p2.py ├── 03 │ ├── p1.py │ └── p2.py ├── 04 │ ├── p1.py │ └── p2.py ├── 05 │ ├── p1.py │ └── p2.py ├── 06 │ ├── p1.py │ └── p2.py ├── 07 │ ├── p1.py │ └── p2.py ├── 08 │ ├── p1.py │ └── p2.py └── 09 │ ├── p1.py │ └── p2.py ├── 2024 ├── 10 │ ├── p1.py │ └── p2.py ├── 11 │ ├── p1.exs │ ├── p1.py │ ├── p2.exs │ └── p2.py ├── 12 │ ├── p1.py │ └── p2.py ├── 13 │ ├── p1.py │ └── p2.py ├── 14 │ ├── p1.py │ └── p2.py ├── 15 │ ├── p1.py │ └── p2.py ├── 16 │ ├── p1.py │ └── p2.py ├── 17 │ ├── p1.py │ └── p2.py ├── 18 │ ├── p1.py │ └── p2.py ├── 19 │ ├── p1.py │ └── p2.py ├── 20 │ ├── p1.py │ └── p2.py ├── 21 │ ├── p1.py │ └── p2.py ├── 22 │ ├── p1.py │ └── p2.py ├── 23 │ ├── p1.py │ └── p2.py ├── 24 │ └── p1.py ├── 25 │ └── p1.py ├── 01 │ ├── p1.exs │ ├── p1.py │ ├── p2.exs │ └── p2.py ├── 02 │ ├── p1.exs │ ├── p1.py │ ├── p2.exs │ └── p2.py ├── 03 │ ├── p1.exs │ ├── p1.py │ ├── p2.exs │ └── p2.py ├── 04 │ ├── p1.py │ └── p2.py ├── 05 │ ├── p1.py │ └── p2.py ├── 06 │ ├── p1.py │ └── p2.py ├── 07 │ ├── p1.py │ └── p2.py ├── 08 │ ├── p1.py │ └── p2.py └── 09 │ ├── p1.py │ └── p2.py ├── .gitignore └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | */*.txt 2 | **/input* 3 | **/test* 4 | **/example* -------------------------------------------------------------------------------- /2015/1/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | l = [sum([1 if c=='(' else -1 for c in l.strip()]) for l in sys.stdin] 4 | print(l) -------------------------------------------------------------------------------- /2015/1/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | l = [[1 if c=='(' else -1 for c in l.strip()] for l in sys.stdin] 4 | for i in l: 5 | pos = 0 6 | for idx,c in enumerate(i): 7 | pos = pos + c 8 | if(pos<0): 9 | print(idx+1) 10 | break -------------------------------------------------------------------------------- /2015/2/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def calc(l,w,h): 4 | a = l*w 5 | b = w*h 6 | c = h*l 7 | return 2*a+2*b+2*c + min(a,min(b,c)) 8 | 9 | l = sum([calc(*([ int(k) for k in l.strip().split("x")])) for l in sys.stdin]) 10 | print(l) -------------------------------------------------------------------------------- /2015/2/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def calc(l,w,h): 4 | x = l+w+h - max(l,w,h) 5 | return l*w*h + 2*x 6 | 7 | l = sum([calc(*([ int(k) for k in l.strip().split("x")])) for l in sys.stdin]) 8 | print(l) -------------------------------------------------------------------------------- /2021/1/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | l =[] 4 | c = 0 5 | 6 | for line in sys.stdin: 7 | l.append(int(line.rstrip())) 8 | if len(l) == 2: 9 | if l[0] < l[1]: 10 | c = c+1 11 | l.pop(0) 12 | print(c) 13 | -------------------------------------------------------------------------------- /2021/1/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | l =[] 4 | c = 0 5 | 6 | for line in sys.stdin: 7 | l.append(int(line.rstrip())) 8 | if len(l) == 4: 9 | if l[0] < l[3]: 10 | c = c+1 11 | l.pop(0) 12 | print(c) 13 | -------------------------------------------------------------------------------- /2021/10/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def process(l): 4 | entry = {'(', '[','{','<'} 5 | close = {')':('(',3), ']':('[',57),'}':('{',1197),'>':('<',25137)} 6 | stack = [] 7 | for c in l: 8 | if c in entry: 9 | stack.append(c) 10 | else: 11 | expected, points = close.get(c) 12 | actual = stack.pop() 13 | if actual!=expected: 14 | return points 15 | return 0 16 | 17 | 18 | 19 | 20 | 21 | l = sum([process(l.strip()) for l in sys.stdin]) 22 | 23 | print(l) -------------------------------------------------------------------------------- /2021/10/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def process(l): 4 | entry = {'(':(')',1), '[':(']',2),'{':('}',3),'<':('>',4)} 5 | close = {')':('(',3), ']':('[',57),'}':('{',1197),'>':('<',25137)} 6 | stack = [] 7 | for c in l: 8 | if c in entry: 9 | stack.append(c) 10 | else: 11 | expected, points = close.get(c) 12 | actual = stack.pop() 13 | if actual!=expected: 14 | return 0 15 | total = 0 16 | while stack: 17 | c = stack.pop() 18 | total = total*5 + entry.get(c)[1] 19 | return total 20 | 21 | 22 | 23 | 24 | 25 | l = [process(l.strip()) for l in sys.stdin] 26 | l = list(filter(lambda x:x!=0,sorted(l))) 27 | print(l[len(l)//2]) -------------------------------------------------------------------------------- /2021/2/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | d=0 5 | h=0 6 | for line in sys.stdin: 7 | c,v = line.rstrip().split(" ") 8 | if c == "forward": 9 | h = h +int(v) 10 | elif c=="up": 11 | d=d-int(v) 12 | elif c=="down": 13 | d=d+int(v) 14 | else: 15 | print("somthing is wrong") 16 | 17 | print(d*h) 18 | -------------------------------------------------------------------------------- /2021/2/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | d = 0 5 | h = 0 6 | a = 0 7 | for line in sys.stdin: 8 | c, x = line.rstrip().split(" ") 9 | x = int(x) 10 | if c == "forward": 11 | h = h + x 12 | d = d+(a*x) 13 | elif c == "up": 14 | a = a-x 15 | elif c == "down": 16 | a = a+x 17 | else: 18 | print("somthing is wrong") 19 | #print(" test a%d h%d d%d c%s x%s"%(a,h,d,c,x)) 20 | 21 | print(d*h) 22 | -------------------------------------------------------------------------------- /2021/3/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | c = [] 4 | t = 0 5 | 6 | # reading input 7 | for line in sys.stdin: 8 | l = line.rstrip() 9 | if c == []: 10 | c = [0]*len(l) 11 | for i, x in enumerate(l): 12 | c[i] = c[i] + (1 if x == '1' else 0) 13 | t = t + 1 14 | 15 | k = 1 16 | g = 0 17 | e = 0 18 | c.reverse() 19 | for b in c: 20 | if b>t/2: 21 | g=g+k 22 | else: 23 | e=e+k 24 | k=k*2 25 | 26 | 27 | print(e*g) 28 | -------------------------------------------------------------------------------- /2021/3/p2.js: -------------------------------------------------------------------------------- 1 | 2 | var readline = require('readline'); 3 | var rl = readline.createInterface({ 4 | input: process.stdin, 5 | output: process.stdout, 6 | terminal: false 7 | }); 8 | 9 | // binary tree :eyes: 10 | class N { 11 | one = undefined 12 | zero = undefined 13 | count = 0 14 | v = undefined 15 | constructor(v) { 16 | this.v = v 17 | } 18 | 19 | push(p) { 20 | this.count++ 21 | if (!p) 22 | return 23 | 24 | this.one = this.one || new N(1) 25 | this.zero = this.zero || new N(0) 26 | if (p[0] == 1) 27 | this.one.push(p.slice(1)) 28 | else 29 | this.zero.push(p.slice(1)) 30 | 31 | } 32 | } 33 | 34 | 35 | //root 36 | var x = new N() 37 | 38 | rl.on('line', function (line) { 39 | x.push(line) 40 | 41 | }) 42 | rl.on('close', () => { process(x) }) 43 | 44 | 45 | 46 | process = (root) => { 47 | let [o, q] = solve(root, 1) 48 | let [c, w] = solve(root, 0) 49 | console.log(o * c) 50 | } 51 | 52 | solve = (x, m) => { 53 | if (!x.one) { 54 | //leaf 55 | return [x.v, 1] 56 | } 57 | 58 | var choose 59 | if (x.count == 1) { 60 | choose = x.one.count ? x.one : x.zero 61 | } else { 62 | a = x.count / 2 <= x.one.count ? x.one : x.zero 63 | b = x.count / 2 <= x.one.count ? x.zero : x.one 64 | 65 | choose = m ? a : b 66 | } 67 | [acc, pow] = solve(choose, m) 68 | pow *= 2 69 | return [(acc + ((x.v || 0) * pow)), pow] 70 | } -------------------------------------------------------------------------------- /2021/4/p1.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | 4 | def readB(b): 5 | l = stdin.readline() 6 | if l == '': 7 | return False 8 | 9 | x = []*5 10 | for i in range(5): 11 | x.append(input().split()) 12 | b.append(x) 13 | return True 14 | 15 | 16 | def test(b): 17 | for i in range(5): 18 | r = c = 0 19 | for j in range(5): 20 | r = r+int(b[i][j]) 21 | c = r+int(b[j][i]) 22 | if r == -5 or c == -5: 23 | return True 24 | return False 25 | 26 | 27 | def win(b): 28 | for a in b: 29 | if test(a): 30 | return True 31 | return False 32 | 33 | 34 | def offer(a, v): 35 | for b in a: 36 | for i in range(5): 37 | for j in range(5): 38 | if b[i][j] == v: 39 | b[i][j] = -1 40 | 41 | 42 | def calcWin(b): 43 | c = 0 44 | for a in b: 45 | if test(a): 46 | for i in range(5): 47 | for j in range(5): 48 | if a[i][j] != -1: 49 | c = c + int(a[i][j]) 50 | return c 51 | 52 | 53 | n = input().split(",") 54 | b = [] 55 | 56 | while readB(b): 57 | continue 58 | 59 | v = 0 60 | while not win(b): 61 | v = n[0] 62 | n = n[1:] 63 | offer(b, v) 64 | 65 | print(calcWin(b)*int(v)) 66 | -------------------------------------------------------------------------------- /2021/4/p2.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | 4 | def readB(b): 5 | l = stdin.readline() 6 | if l == '': 7 | return False 8 | 9 | x = []*5 10 | for i in range(5): 11 | x.append(input().split()) 12 | b.append(x) 13 | return True 14 | 15 | 16 | def test(b): 17 | for i in range(5): 18 | r = c = 0 19 | for j in range(5): 20 | r = r+int(b[i][j]) 21 | c = c+int(b[j][i]) 22 | if r == -5 or c == -5: 23 | return True 24 | return False 25 | 26 | 27 | def win(b): 28 | for a in b: 29 | if test(a): 30 | return True 31 | return False 32 | def removeWin(b): 33 | for a in b: 34 | if test(a): 35 | b.remove(a) 36 | 37 | 38 | def offer(a, v): 39 | for b in a: 40 | for i in range(5): 41 | for j in range(5): 42 | if b[i][j] == v: 43 | b[i][j] = -1 44 | 45 | 46 | def calcWin(b): 47 | c = 0 48 | for a in b: 49 | for i in range(5): 50 | for j in range(5): 51 | if a[i][j] != -1: 52 | c = c + int(a[i][j]) 53 | return c 54 | 55 | 56 | n = input().split(",") 57 | 58 | b = [] 59 | 60 | while readB(b): 61 | continue 62 | 63 | 64 | v = 0 65 | while not win(b) or len(b)>1: 66 | removeWin(b) 67 | v = n[0] 68 | n = n[1:] 69 | offer(b, v) 70 | print(calcWin(b)*int(v)) 71 | -------------------------------------------------------------------------------- /2021/5/p1.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | 4 | def offer(a, b, c): 5 | aux = a.split(",") 6 | x1 = int(aux[0]) 7 | y1 = int(aux[1]) 8 | 9 | aux = b.split(",") 10 | x2 = int(aux[0]) 11 | y2 = int(aux[1]) 12 | 13 | if x1 == x2: 14 | for i in range(min(y1, y2), max(y1,y2)+1): 15 | print(x1, i, "x") 16 | c[x1][i] = c[x1][i] + 1 17 | 18 | if y1 == y2: 19 | for i in range(min(x1, x2), max(x1,x2)+1): 20 | print(i, y1, "y") 21 | c[i][y1] = c[i][y1] + 1 22 | 23 | size=1000 24 | c = [[0 for x in range(size)] for y in range(size)] 25 | 26 | for line in stdin: 27 | n = line.rstrip().split(" -> ") 28 | offer(n[0], n[1], c) 29 | print(n) 30 | 31 | r =0 32 | for l in c: 33 | for d in l: 34 | print(d,",", end="") 35 | if d>=2: 36 | r=r+1 37 | print("") 38 | 39 | print(r) -------------------------------------------------------------------------------- /2021/5/p2.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | 4 | def offer(a, b, c): 5 | aux = a.split(",") 6 | x1 = int(aux[0]) 7 | y1 = int(aux[1]) 8 | 9 | aux = b.split(",") 10 | x2 = int(aux[0]) 11 | y2 = int(aux[1]) 12 | 13 | if x1 == x2: 14 | for i in range(min(y1, y2), max(y1, y2)+1): 15 | #print(x1, i, "x") 16 | c[x1][i] = c[x1][i] + 1 17 | 18 | elif y1 == y2: 19 | for i in range(min(x1, x2), max(x1, x2)+1): 20 | #print(i, y1, "y") 21 | c[i][y1] = c[i][y1] + 1 22 | else: 23 | xs = min(x1, x2) 24 | ys = y1 if xs == x1 else y2 25 | ye = y1 if xs != x1 else y2 26 | s = 1 if ye>ys else -1 27 | for i in range(ys, ye+s, s): 28 | #print(xs, i, "m", ys, ye, s) 29 | c[xs][i] = c[xs][i]+1 30 | xs = xs+1 31 | 32 | 33 | size = 1000 34 | c = [[0 for x in range(size)] for y in range(size)] 35 | 36 | for line in stdin: 37 | n = line.rstrip().split(" -> ") 38 | offer(n[0], n[1], c) 39 | print(n) 40 | 41 | r = 0 42 | for l in c: 43 | for d in l: 44 | #print(d if d!=0 else '.', ",", end="") 45 | if d >= 2: 46 | r = r+1 47 | #print("") 48 | 49 | print(r) 50 | -------------------------------------------------------------------------------- /2021/6/p1.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | 4 | size = 10 5 | c = [0 for x in range(size)] 6 | 7 | 8 | for i in stdin.readline().split(","): 9 | c[int(i)] = c[int(i)]+1 10 | print(c) 11 | 12 | for i in range(80): 13 | for j in range(9): 14 | if j==0: 15 | c[9]=c[0] 16 | c[7]=c[7]+c[0] 17 | c[j]=c[j+1] 18 | c[9]=0 19 | print(i+1, c, sum(c)) 20 | print(sum(c)) -------------------------------------------------------------------------------- /2021/6/p2.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | 4 | size = 10 5 | c = [0 for x in range(size)] 6 | 7 | 8 | for i in stdin.readline().split(","): 9 | c[int(i)] = c[int(i)]+1 10 | print(c) 11 | 12 | for i in range(256): 13 | for j in range(9): 14 | if j==0: 15 | c[9]=c[0] 16 | c[7]=c[7]+c[0] 17 | c[j]=c[j+1] 18 | c[9]=0 19 | print(i+1, c, sum(c)) 20 | print(sum(c)) -------------------------------------------------------------------------------- /2021/7/p1.py: -------------------------------------------------------------------------------- 1 | import math 2 | from sys import stdin 3 | 4 | 5 | n= [int(x) for x in stdin.readline().split(",")] 6 | 7 | n.sort() 8 | l = len(n) 9 | a = math.ceil(l/2) 10 | b = math.floor(l/2) 11 | 12 | dest = (n[a]+n[b])/2 13 | 14 | r = sum([abs(x-dest) for x in n]) 15 | print(r) -------------------------------------------------------------------------------- /2021/7/p2.py: -------------------------------------------------------------------------------- 1 | import math 2 | from sys import stdin 3 | 4 | def msum(n): 5 | return (n*(n+1))/2 6 | n= [int(x) for x in stdin.readline().split(",")] 7 | 8 | n.sort() 9 | l = len(n) 10 | 11 | # workaround... example should use ceil, input should use floor 12 | dest = math.floor((sum(n))/l) 13 | 14 | r = sum([msum(abs(x-dest)) for x in n]) 15 | print(dest, r) -------------------------------------------------------------------------------- /2021/9/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def edges(i,j): 4 | e = [] 5 | #top 6 | if(i>0): 7 | e.append((i-1,j)) 8 | #left 9 | if(j>0): 10 | e.append((i,j-1)) 11 | #down 12 | if(i+10): 8 | e.append((i-1,j)) 9 | #left 10 | if(j>0): 11 | e.append((i,j-1)) 12 | #down 13 | if(i+1 @@input:split("\n\n")|> (_:split("\n")|>_#:sum) |> max(_) as result at the end -------------------------------------------------------------------------------- /2022/1/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | ## elfs 4 | l =[0] 5 | ## max 6 | m = 0 7 | 8 | ## index 9 | i=0 10 | 11 | for line in sys.stdin: 12 | line = line.rstrip() 13 | if(line == ""): 14 | i = i + 1 15 | l.append(0) 16 | else: 17 | l[i] = l[i] + int(line) 18 | m = max(m, l[i]) 19 | print(m) 20 | -------------------------------------------------------------------------------- /2022/1/p2.pipe: -------------------------------------------------------------------------------- 1 | def @@input: "PAST YOUR INPUT HERE"; 2 | 3 | => @@input:split("\n\n")|> (_:split("\n")|>_#:sum) |> @top( 3, _ desc)|>_#sum as result at the end -------------------------------------------------------------------------------- /2022/1/p2.py: -------------------------------------------------------------------------------- 1 | import heapq as hq 2 | import sys 3 | 4 | ## elfs 5 | l =[0] 6 | ## max 7 | m = 0 8 | 9 | k = 3 10 | minHeap = [] 11 | ## index 12 | i=0 13 | 14 | for line in sys.stdin: 15 | line = line.rstrip() 16 | if(line == ""): 17 | hq.heappush(minHeap, l[i]) 18 | if(i>=k): 19 | hq.heappop(minHeap) 20 | i = i + 1 21 | l.append(0) 22 | else: 23 | l[i] = l[i] + int(line) 24 | 25 | hq.heappush(minHeap, l[i]) 26 | if(i>=k): 27 | hq.heappop(minHeap) 28 | 29 | sum = 0 30 | for v in minHeap: 31 | sum = sum + v 32 | print(sum) 33 | -------------------------------------------------------------------------------- /2022/10/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | prints = False 4 | 5 | size = 300 6 | cycle = [1]*size 7 | i = 1 8 | 9 | for l in [i.rstrip() for i in sys.stdin]: 10 | i=i+1 11 | cycle[i]=cycle[i-1] 12 | if(l[0] == 'a'): 13 | i=i+1 14 | cycle[i] = cycle[i-1] + int(l.split(" ")[1]) 15 | if prints: 16 | print(l.split(" ")[0], cycle[max(0,i-5):i+1], i ) 17 | 18 | for t in range(i+1, size): 19 | cycle[t]=cycle[t-1] 20 | 21 | r = 0 22 | for i in range(6): 23 | r = r + cycle[20+ 40*i]*(20+40*i) 24 | print(r) -------------------------------------------------------------------------------- /2022/10/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | prints = False 4 | 5 | def printa (x, pos, r): 6 | print("Sprint: ", end="") 7 | for i in range(40): 8 | print("🟥" if i>= x-1 and i<=x+1 else "⬛️", end="") 9 | print("\nstarting cycle", pos, " X = ", x, "will print: ", "🟥" if r else "⬛️" ) 10 | print("\n") 11 | 12 | 13 | def test(x, pos): 14 | pos = (pos%40) 15 | r= pos >=(x-1) and pos<=(x+1) 16 | if prints: 17 | printa(x, pos, r) 18 | return r 19 | 20 | 21 | size = 300 22 | cycle = [1]*size 23 | i = 1 24 | 25 | for l in [i.rstrip() for i in sys.stdin]: 26 | i=i+1 27 | cycle[i]=cycle[i-1] 28 | if(l[0] == 'a'): 29 | i=i+1 30 | cycle[i] = cycle[i-1] + int(l.split(" ")[1]) 31 | if prints: 32 | print(l.split(" ")[0], cycle[max(0,i-5):i+1], i ) 33 | 34 | for t in range(i+1, size): 35 | cycle[t]=cycle[t-1] 36 | 37 | resp = "" 38 | for i in range(6): 39 | for j in range(40): 40 | pos = i*40 + j 41 | resp = resp + ( "🟥" if test(cycle[pos+1],pos) else "⬛️") 42 | resp= resp+ "\n" 43 | print(resp) -------------------------------------------------------------------------------- /2022/11/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from math import inf, prod 3 | 4 | prints = False 5 | 6 | class Monkey: 7 | def __init__(self, l): 8 | self.id = l[0][-2] 9 | self.items = [ int(k.strip()) for k in l[1].split(":")[1].split(",")] 10 | self.op, factor = l[2].split(" ")[-2:] 11 | self.factor = int(factor) if factor != "old" else inf 12 | self.div = int(l[3].split(" ")[-1]) 13 | self.t = int(l[4].split(" ")[-1]) 14 | self.f = int(l[5].split(" ")[-1]) 15 | self.c = 0 16 | def process(self, mk): 17 | if prints: 18 | print("Monkey", self.id) 19 | while len(self.items)>0: 20 | self.c=self.c+1 21 | i = self.items.pop(0) 22 | n = i if self.factor == inf else self.factor 23 | 24 | if prints: 25 | print("Olhando para o ", i, self.op, n, end="") 26 | if(self.op == "*"): 27 | i = i * n 28 | else: 29 | i = i + n 30 | i = i//3 31 | if prints: 32 | print("=", i, " ", i,"%", self.div, " ", i%self.div==0) 33 | if i % self.div == 0: 34 | mk[self.t].items.append(i) 35 | if prints: 36 | print("mandou para o ", self.t) 37 | else: 38 | mk[self.f].items.append(i) 39 | if prints: 40 | print("mandou para o ", self.f) 41 | 42 | 43 | 44 | l = [i.rstrip() for i in sys.stdin] 45 | 46 | 47 | mk = [] 48 | 49 | i = 0 50 | while i0: 20 | self.c=self.c+1 21 | i = self.items.pop(0) 22 | n = i if self.factor == inf else self.factor 23 | 24 | if prints: 25 | print("Olhando para o ", i, self.op, n, end="") 26 | if(self.op == "*"): 27 | i = (i * n ) 28 | else: 29 | i = (i + n) 30 | i = i%mod 31 | if prints: 32 | print("=", i, " ", i,"%", self.div, " ", i%self.div==0) 33 | target = self.t if i%self.div == 0 else self.f 34 | mk[target].items.append(i) 35 | if prints: 36 | print("mandou para o ", target) 37 | 38 | 39 | 40 | l = [i.rstrip() for i in sys.stdin] 41 | 42 | 43 | mk = [] 44 | 45 | i = 0 46 | while i0: 18 | n,c = q.pop() #node, cost 19 | if cost[n] != c: 20 | continue #already found a better path for n 21 | for v in mat[n]: 22 | if(cost[v] > (c+1)): 23 | cost[v]=c+1 24 | q.append((v,c+1)) 25 | 26 | 27 | 28 | 29 | l = [l.rstrip() for l in sys.stdin] 30 | 31 | lines = len(l) 32 | cols = len(l[0]) 33 | 34 | 35 | mat = [] 36 | for i in range(lines): 37 | for j in range(cols): 38 | pos = j + i*cols 39 | v = l[i][j] 40 | if(v=="S"): 41 | start = pos 42 | if(l[i][j]=="E"): 43 | end = pos 44 | adj = [] 45 | #top 46 | if(i>0 and check(v, l[i-1][j])): 47 | adj.append(j + (i-1)*cols) 48 | #left 49 | if(j>0 and check(v, l[i][j-1])): 50 | adj.append(j-1+i*cols) 51 | #down 52 | if(i+1=(a-1) #inverted from part1 14 | def dijkstra(start, mat, cost): 15 | q = [] 16 | cost[start] = 0 17 | q.append((start, 0)) 18 | while len(q)>0: 19 | n,c = q.pop() #node, cost 20 | if cost[n] != c: 21 | continue #already found a better path for n 22 | for v in mat[n]: 23 | if(cost[v] > (c+1)): 24 | cost[v]=c+1 25 | q.append((v,c+1)) 26 | 27 | 28 | 29 | 30 | l = [l.rstrip() for l in sys.stdin] 31 | 32 | lines = len(l) 33 | cols = len(l[0]) 34 | 35 | mat = [] 36 | for i in range(lines): 37 | for j in range(cols): 38 | pos = j + i*cols 39 | v = l[i][j] 40 | if(v=="S"): 41 | start = pos 42 | if(l[i][j]=="E"): 43 | end = pos 44 | adj = [] 45 | #top 46 | if(i>0 and check(v, l[i-1][j])): 47 | adj.append(j + (i-1)*cols) 48 | #left 49 | if(j>0 and check(v, l[i][j-1])): 50 | adj.append(j-1+i*cols) 51 | #down 52 | if(i+1b else -1 8 | def compare(a,b): 9 | i = 0 10 | while ib else -1 11 | def compare(a,b): 12 | i = 0 13 | while i=0 and j>=0 and imaxY): 29 | return False 30 | mat[pos[0]][pos[1]]='o' 31 | return True 32 | 33 | def printa(): 34 | poi = [[i,j] for i,k in enumerate(mat) for j,v in enumerate(k[:-1]) if v!='.' ] 35 | maxX = max(poi, key= lambda y: y[0])[0] 36 | maxY = max(poi, key= lambda y: y[1])[1] 37 | minX = min(poi, key= lambda y: y[0])[0] 38 | minY = min(poi, key= lambda y: y[1])[1] 39 | for j in range(minY, maxY+1): 40 | for i in range(minX, maxX+1): 41 | print(mat[i][j], end="") 42 | print("") 43 | 44 | lines = [[ [int(j) for j in i.strip().split(",")] for i in l.split("->")] for l in sys.stdin] 45 | 46 | maxY = max([max(k, key= lambda y: y[1])[1] for k in lines]) 47 | 48 | mat = [] 49 | for i in range(2000): 50 | mat.append(['.']*(maxY+3)) 51 | 52 | for line in lines: 53 | src = line[0] 54 | for i in range(1, len(line)): 55 | dest = line[i] 56 | 57 | deltaX = dest[0]-src[0] 58 | deltaY = dest[1]-src[1] 59 | mov = [0 if deltaX ==0 else deltaX//abs(deltaX), 0 if deltaY ==0 else deltaY//abs(deltaY)] 60 | while src != dest: 61 | mat[src[0]][src[1]] = '#' 62 | src = [src[0]+mov[0], src[1]+mov[1]] 63 | mat[src[0]][src[1]] = '#' 64 | 65 | printa() 66 | 67 | c = 0 68 | while drop(): 69 | c = c+1 70 | if(c%1000==0): 71 | print(c) 72 | printa() 73 | printa() 74 | print(c) -------------------------------------------------------------------------------- /2022/14/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def check(pos, i,j): 5 | i = i + pos[0] 6 | j = j + pos[1] 7 | return i>=0 and j>=0 and i")] for l in sys.stdin] 45 | 46 | maxY = max([max(k, key= lambda y: y[1])[1] for k in lines]) 47 | 48 | mat = [] 49 | for i in range(2000): 50 | mat.append(['.']*(maxY+3)) 51 | 52 | for line in lines: 53 | src = line[0] 54 | for i in range(1, len(line)): 55 | dest = line[i] 56 | 57 | deltaX = dest[0]-src[0] 58 | deltaY = dest[1]-src[1] 59 | mov = [0 if deltaX ==0 else deltaX//abs(deltaX), 0 if deltaY ==0 else deltaY//abs(deltaY)] 60 | while src != dest: 61 | mat[src[0]][src[1]] = '#' 62 | src = [src[0]+mov[0], src[1]+mov[1]] 63 | mat[src[0]][src[1]] = '#' 64 | 65 | 66 | for i in range(len(mat)): 67 | mat[i][maxY+2] = '#' 68 | printa() 69 | 70 | c = 0 71 | while drop(): 72 | c = c+1 73 | if(c%1000==0): 74 | print(c) 75 | printa() 76 | printa() 77 | print(c) -------------------------------------------------------------------------------- /2022/15/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def convert(l): 4 | l = l.strip() 5 | p = l.split(" ") 6 | x1 = int(p[2].split("=")[1].split(",")[0]) 7 | y1 = int(p[3].split("=")[1].split(":")[0]) 8 | 9 | 10 | x2 = int(p[8].split("=")[1].split(",")[0]) 11 | y2 = int(p[9].split("=")[1]) 12 | 13 | return [(x1,y1), (x2,y2), abs(x1-x2) + abs(y1-y2)] 14 | lines = [convert(l) for l in sys.stdin] 15 | #Sensor at x=2, y=18: closest beacon is at x=-2, y=15 16 | 17 | target = 2000000 18 | segments = [] 19 | for l in lines: 20 | s,_,dist = l 21 | x,y = s 22 | a = dist - abs(target-y) 23 | if(a>=0): 24 | seg = (x-a,x+a) 25 | print("adding ", seg,a, s,dist) 26 | segments.append(seg) 27 | segments = sorted(segments) 28 | [print(i) for i in segments] 29 | total = 0 30 | s,e = segments[0] 31 | for i in range(1, len(segments)): 32 | ns,ne = segments[i] 33 | if(ns>e): #different segment 34 | print("size", s,e, ns,ne) 35 | total = total + e-s 36 | s,e = ns,ne 37 | else: 38 | e = max(e,ne) 39 | print("size", s,e) 40 | total = total + e-s 41 | print(total) 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /2022/15/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def convert(l): 4 | l = l.strip() 5 | p = l.split(" ") 6 | x1 = int(p[2].split("=")[1].split(",")[0]) 7 | y1 = int(p[3].split("=")[1].split(":")[0]) 8 | 9 | 10 | x2 = int(p[8].split("=")[1].split(",")[0]) 11 | y2 = int(p[9].split("=")[1]) 12 | 13 | return [(x1,y1), (x2,y2), abs(x1-x2) + abs(y1-y2)] 14 | lines = [convert(l) for l in sys.stdin] 15 | #Sensor at x=2, y=18: closest beacon is at x=-2, y=15 16 | 17 | 18 | maxTarget = 4000000 19 | 20 | rx = 0 21 | ry = 0 22 | for target in range(maxTarget): 23 | segments = [] 24 | for l in lines: 25 | s,_,dist = l 26 | x,y = s 27 | a = dist - abs(target-y) 28 | if(a>=0): 29 | seg = (max(0,x-a),min(maxTarget,x+a)) 30 | segments.append(seg) 31 | segments = sorted(segments) 32 | total = 0 33 | s,e = segments[0] 34 | for i in range(1, len(segments)): 35 | ns,ne = segments[i] 36 | if(ns>e): #different segment 37 | s,e = ns,ne 38 | ry = target 39 | rx=ns-1 40 | 41 | break 42 | else: 43 | e = max(e,ne) 44 | else: 45 | continue 46 | break 47 | 48 | 49 | print(rx,ry,ry+ rx*4000000) 50 | """ 51 | real 0m23,415s 52 | user 0m23,382s 53 | sys 0m0,014s 54 | """ -------------------------------------------------------------------------------- /2022/16/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | 5 | def extractNode(l): 6 | #Valve JJ has flow rate=21; tunnel leads to valve II 7 | s = l.split(" ") 8 | id = s[1] 9 | rate = int(s[4].split("=")[1][:-1]) 10 | links = [i.strip() for i in " ".join(s[9:]).split(",")] 11 | return id,rate,links 12 | 13 | def bfs(g,v,t): #graph, value, targets 14 | d = {v:0} #dist 15 | s = {v} #seen 16 | q = deque([v]) #queue 17 | while q and any(k not in d for k in t): 18 | p = q.popleft() 19 | for u in g[p]: 20 | if u not in s: 21 | s.add(u) 22 | d[u] = d[p]+1 23 | q.append(u) 24 | return d 25 | 26 | 27 | def dfs(v, dist, rates, time, p = []): 28 | p = p+[v] 29 | if(time<=0 or len(p)==len(rates)): 30 | return 0 31 | tot = 0 32 | for n,d in dist[v].items(): 33 | if d>time-2 or n in p: 34 | continue 35 | nt = time-d-1 36 | tot = max(tot, dfs(n,dist, rates, nt, p)+rates[n]*(nt)) 37 | return tot 38 | 39 | def find_paths(dist, rates, t): # dist, rates, max time 40 | pressures = [] 41 | paths = [] 42 | stack = [(t, 0, ['AA'])] #current time, pressure, path 43 | while stack: 44 | t, p, path = stack.pop() 45 | cur = path[-1] 46 | new = [] #new paths from here 47 | for n, d in dist[cur].items(): #neighbor, distance 48 | if d > t - 2 or n in path: # can I reach? or Did I pass there already? 49 | continue 50 | tt = t - d - 1 #total time = time - distance -1 (turn the valve on) 51 | pp = p + rates[n] * tt #pressure = current pressure + preasure release by n valve 52 | s = tt, pp, path + [n] # include n into path 53 | new.append(s) # and this new to new paths 54 | if new: 55 | stack.extend(new) 56 | else: 57 | pressures.append(p) 58 | # paths always start at AA, so no need to keep first location 59 | paths.append(path[1:]) 60 | return pressures, paths 61 | 62 | 63 | rates = {} 64 | links = {} 65 | for l in sys.stdin: 66 | id, rate, link = extractNode(l) 67 | if(rate>0): 68 | rates[id]= rate 69 | links[id] = link 70 | 71 | dist = {} 72 | for v in ('AA', *rates): 73 | dist[v]={} 74 | d = bfs(links, v, rates) 75 | for r in rates: 76 | if r!= v and r in d: 77 | dist[v][r]=d[r] 78 | print(dist) 79 | 80 | p, _ = find_paths(dist, rates, 30) 81 | print(max(p)) 82 | 83 | 84 | 85 | 86 | 87 | print(dfs("AA",dist, rates, 30)) -------------------------------------------------------------------------------- /2022/16/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | 5 | def extractNode(l): 6 | #Valve JJ has flow rate=21; tunnel leads to valve II 7 | s = l.split(" ") 8 | id = s[1] 9 | rate = int(s[4].split("=")[1][:-1]) 10 | links = [i.strip() for i in " ".join(s[9:]).split(",")] 11 | return id,rate,links 12 | 13 | def bfs(g,v,t): #graph, value, targets 14 | d = {v:0} #dist 15 | s = {v} #seen 16 | q = deque([v]) #queue 17 | while q and any(k not in d for k in t): 18 | p = q.popleft() 19 | for u in g[p]: 20 | if u not in s: 21 | s.add(u) 22 | d[u] = d[p]+1 23 | q.append(u) 24 | return d 25 | 26 | def dfs(v, dist, rates, time, p2= False, p = []): 27 | if(printa): 28 | print('looking',v,p2, p) 29 | p = p+[v] 30 | if(time<=0 or len(p)>len(rates)): 31 | return 0 32 | tot = 0 33 | for n,d in dist[v].items(): 34 | if d>time-2 or n in p: 35 | continue 36 | nt = time-d-1 37 | tot = max(tot, dfs(n,dist, rates, nt, p2, p)+rates[n]*(nt)) 38 | return tot + (dfs("AA", dist,rates,26,False, p) if p2 else 0) 39 | 40 | def find_paths(dist, rates, t): # dist, rates, max time 41 | pressures = [] 42 | paths = [] 43 | stack = [(t, 0, ['AA'])] #current time, pressure, path 44 | while stack: 45 | t, p, path = stack.pop() 46 | cur = path[-1] 47 | new = [] #new paths from here 48 | for n, d in dist[cur].items(): #neighbor, distance 49 | if d > t - 2 or n in path: # can I reach? or Did I pass there already? 50 | continue 51 | tt = t - d - 1 #total time = time - distance -1 (turn the valve on) 52 | pp = p + rates[n] * tt #pressure = current pressure + preasure release by n valve 53 | s = tt, pp, path + [n] # include n into path 54 | new.append(s) # and this new to new paths 55 | if new: 56 | stack.extend(new) 57 | else: 58 | pressures.append(p) 59 | # paths always start at AA, so no need to keep first location 60 | paths.append(path[1:]) 61 | return pressures, paths 62 | 63 | 64 | rates = {} 65 | links = {} 66 | for l in sys.stdin: 67 | id, rate, link = extractNode(l) 68 | if(rate>0): 69 | rates[id]= rate 70 | links[id] = link 71 | 72 | dist = {} 73 | for v in ('AA', *rates): 74 | dist[v]={} 75 | d = bfs(links, v, rates) 76 | for r in rates: 77 | if r!= v and r in d: 78 | dist[v][r]=d[r] 79 | 80 | p, _ = find_paths(dist, rates, 30) 81 | print(max(p)) 82 | 83 | printa = False 84 | 85 | print(dfs("AA",dist, rates, 30)) 86 | 87 | 88 | 89 | printa = True 90 | print(dfs("AA",dist, rates, 26, True)) 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /2022/17/p1.py: -------------------------------------------------------------------------------- 1 | from itertools import cycle 2 | import sys 3 | 4 | def apply(pice, x,y, clean = False): 5 | for i in pice: 6 | aux = y-1 7 | for j in i: 8 | aux = aux +1 9 | if(j==" "): 10 | continue 11 | tab[x][aux]= j if not clean else "." 12 | x= x-1 13 | 14 | def check(pice, x, y): 15 | #print("check", pice, x,y) 16 | size = len(pice) 17 | if(y<0 or y+len(pice[0])>7 or (x-size+1)<0): 18 | #print("fora do mapa") 19 | return False 20 | for i in pice: 21 | aux = y-1 22 | for j in i: 23 | aux = aux +1 24 | #print(x,aux, j, tab[x][aux]) 25 | if j!=" " and tab[x][aux]!=".": 26 | #print("bateu") 27 | return False 28 | x = x -1 29 | return True 30 | 31 | def printTab(pice=None): 32 | if pice: 33 | p,x,y = pice 34 | apply(p,x,y) 35 | 36 | first = True 37 | for i in range(len(tab)): 38 | row = tab[-1-i] 39 | if(first and row==['.']*7): 40 | continue 41 | else: 42 | first=False 43 | print("|"+"".join(row)+"|") 44 | print("+-------+") 45 | if(pice): 46 | p,x,y = pice 47 | apply(p,x,y, True) 48 | 49 | 50 | tab = [] 51 | for i in range(14*2022): 52 | tab.append(['.']*7) 53 | 54 | l = sys.stdin.readline().strip() 55 | mov = cycle(l) 56 | 57 | height = 0 58 | 59 | 60 | 61 | pices = [ 62 | ["####"], 63 | 64 | [" # ", # 65 | "###", 66 | " # "], 67 | 68 | [" #", 69 | " #", 70 | "###"], 71 | 72 | ["#", # 73 | "#", 74 | "#", 75 | "#"], 76 | 77 | ["##", # 78 | "##"] 79 | ] 80 | 81 | 82 | for i in range(2022): 83 | #print("height", height) 84 | pice = pices[i%5] 85 | y = 2 86 | x = height+2+len(pice) 87 | #printTab((pice, x, y)) 88 | for m in mov: #endless loop 89 | ny = y + (-1 if m=='<' else 1) 90 | #printTab((pice, x, y)) 91 | if(check(pice, x,ny)): 92 | y=ny 93 | #printTab((pice, x, y)) 94 | if(check(pice, x-1, y)): 95 | x=x-1 96 | #printTab((pice, x, y)) 97 | else: 98 | break 99 | apply(pice, x,y) 100 | #print("height", height, x, len(pice)) 101 | height = max(height,x+1) 102 | 103 | 104 | 105 | print(height) -------------------------------------------------------------------------------- /2022/17/p2.py: -------------------------------------------------------------------------------- 1 | from itertools import cycle 2 | import sys 3 | 4 | def top(x): 5 | resp = [] 6 | for i in range(heightPattern): 7 | resp.extend(tab[x-i]) 8 | return tuple(resp) 9 | 10 | def apply(pice, x,y, clean = False): 11 | for i in pice: 12 | aux = y-1 13 | for j in i: 14 | aux = aux +1 15 | if(j==" "): 16 | continue 17 | tab[x][aux]= j if not clean else "." 18 | x= x-1 19 | 20 | def check(pice, x, y): 21 | #print("check", pice, x,y) 22 | size = len(pice) 23 | if(y<0 or y+len(pice[0])>7 or (x-size+1)<0): 24 | #print("fora do mapa") 25 | return False 26 | for i in pice: 27 | aux = y-1 28 | for j in i: 29 | aux = aux +1 30 | #print(x,aux, j, tab[x][aux]) 31 | if j!=" " and tab[x][aux]!=".": 32 | #print("bateu") 33 | return False 34 | x = x -1 35 | return True 36 | 37 | def printTab(pice=None): 38 | if pice: 39 | p,x,y = pice 40 | apply(p,x,y) 41 | 42 | first = True 43 | for i in range(len(tab)): 44 | row = tab[-1-i] 45 | if(first and row==['.']*7): 46 | continue 47 | else: 48 | first=False 49 | print("|"+"".join(row)+"|") 50 | print("+-------+") 51 | if(pice): 52 | p,x,y = pice 53 | apply(p,x,y, True) 54 | 55 | 56 | tab = [] 57 | for i in range(14*2022): 58 | tab.append(['.']*7) 59 | 60 | l = sys.stdin.readline().strip() 61 | mov = cycle(l) 62 | 63 | height = 0 64 | 65 | 66 | 67 | pices = [ 68 | ["####"], 69 | 70 | [" # ", # 71 | "###", 72 | " # "], 73 | 74 | [" #", 75 | " #", 76 | "###"], 77 | 78 | ["#", # 79 | "#", 80 | "#", 81 | "#"], 82 | 83 | ["##", # 84 | "##"] 85 | ] 86 | 87 | MAX = 1_000_000_000_000 88 | heightPattern = 20 89 | jet = 0 90 | patMap = dict() 91 | found = False 92 | skipI = 0 93 | skipH = 0 94 | 95 | for i in range(MAX): 96 | if (i + skipI) >= MAX: 97 | break 98 | #print("height", height, i, 1514285714288) 99 | pice = pices[i%5] 100 | y = 2 101 | x = height+2+len(pice) 102 | #printTab((pice, x, y)) 103 | for m in mov: #endless loop 104 | ny = y + (-1 if m=='<' else 1) 105 | #printTab((pice, x, y)) 106 | if(check(pice, x,ny)): 107 | y=ny 108 | jet = jet+1 109 | #printTab((pice, x, y)) 110 | if(check(pice, x-1, y)): 111 | x=x-1 112 | #printTab((pice, x, y)) 113 | else: 114 | break 115 | apply(pice, x,y) 116 | #print("height", height, x, len(pice)) 117 | height = max(height,x+1) 118 | if jet > len(l) and not found: 119 | pat = (jet%len(l), i%5, top(x)) 120 | if pat not in patMap: 121 | patMap[pat] = (height,i) 122 | continue 123 | found = True 124 | lastHeight , lastI = patMap[pat] 125 | diffHeigh = height - lastHeight 126 | diffI = i - lastI 127 | 128 | remain = MAX - i 129 | if(remain < diffI): 130 | continue 131 | 132 | skip = remain // diffI 133 | 134 | remain = remain % diffI 135 | skipH = diffHeigh * skip 136 | skipI = (MAX - remain)-i 137 | print("skip", skipH, skipI) 138 | print(i+skipI) 139 | print(height + skipH) 140 | 141 | #1591860465110 -------------------------------------------------------------------------------- /2022/18/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def sides(x, y, z): 4 | yield (x + 1, y, z) 5 | yield (x - 1, y, z) 6 | yield (x, y + 1, z) 7 | yield (x, y - 1, z) 8 | yield (x, y, z + 1) 9 | yield (x, y, z - 1) 10 | 11 | p = [tuple([int(k) for k in l.strip().split(",")]) for l in sys.stdin] 12 | size = 30 13 | total = 0 14 | for pt in p: 15 | for side in sides(*pt): 16 | if(side not in p): 17 | total = total+1 18 | print(total) 19 | -------------------------------------------------------------------------------- /2022/18/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | def sides(x, y, z): 5 | yield (x + 1, y, z) 6 | yield (x - 1, y, z) 7 | yield (x, y + 1, z) 8 | yield (x, y - 1, z) 9 | yield (x, y, z + 1) 10 | yield (x, y, z - 1) 11 | def outside(x,y,z): 12 | return x<0 or y<0 or z<0 or x>=size or y>=size or z>=size 13 | 14 | def bfs(v): 15 | seen = {v} 16 | q = deque([v]) #queue 17 | while q: 18 | p = q.popleft() 19 | if(p == (0,0,0)): 20 | return True 21 | for side in sides(*p): 22 | if(side in seen): 23 | continue 24 | if(outside(*side)): 25 | return True 26 | if(side not in points): 27 | seen.add(side) 28 | q.append(side) 29 | return False 30 | 31 | points = [tuple([int(k) for k in l.strip().split(",")]) for l in sys.stdin] 32 | 33 | size = 30 34 | total = 0 35 | for pt in points: 36 | for side in sides(*pt): 37 | if(side not in points and bfs(side)): 38 | total = total+1 39 | print(total) -------------------------------------------------------------------------------- /2022/18/pr.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | def sides(x, y, z): 5 | yield (x + 1, y, z) 6 | yield (x - 1, y, z) 7 | yield (x, y + 1, z) 8 | yield (x, y - 1, z) 9 | yield (x, y, z + 1) 10 | yield (x, y, z - 1) 11 | 12 | def outside(x,y,z): 13 | return x<-1 or y<-1 or z<-1 or x>size+1 or y>size+1 or z>size+1 14 | 15 | def bfs(v): 16 | seen = {v} 17 | q = deque([v]) #queue 18 | while q: 19 | for side in sides(*q.popleft()): 20 | if(side in points or side in seen or outside(*side)): 21 | continue 22 | seen.add(side) 23 | q.append(side) 24 | return seen 25 | 26 | points = [tuple([int(k) for k in l.strip().split(",")]) for l in sys.stdin] 27 | size = max( [max(l) for l in points]) 28 | outised = bfs((size-1,size-1,size-1)) #only for part2 29 | 30 | p1 = p2 = 0 31 | for pt in points: 32 | for side in sides(*pt): 33 | if(side not in points): 34 | p1 = p1 +1 35 | if(side in outised): 36 | p2 = p2+1 37 | print(p1,p2) -------------------------------------------------------------------------------- /2022/19/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | from math import prod 4 | def maxPos(current, times): 5 | x = current 6 | y = current+times 7 | return y*(y-1)/2 - x*(x-1)/2 8 | def convert(l): 9 | p = l.split(" ") 10 | id = int(p[1][:-1]) 11 | oreOreCost= int(p[6]) 12 | clayOreCost= int(p[12]) 13 | obOreCost= int(p[18]) 14 | obClayCost= int(p[21]) 15 | GeodeOreCost= int(p[27]) 16 | GeodeObCost= int(p[30]) 17 | return (id, oreOreCost, clayOreCost, obOreCost, obClayCost, GeodeOreCost, GeodeObCost) 18 | 19 | def process(id, oreOreCost, clayOreCost, obOreCost, obClayCost, GeodeOreCost, GeodeObCost, MAX): 20 | types = [ 21 | [oreOreCost, 0,0,0], 22 | [clayOreCost, 0,0,0], 23 | [obOreCost, obClayCost,0,0], 24 | [GeodeOreCost,0,GeodeObCost,0] 25 | ] 26 | limit = [ max([types[k][i] for k in range(4)])*2 for i in range(4)] 27 | limit[3]=999999999999 28 | 29 | resource = (0,0,0,0) #ore, clay,ob,geode 30 | robot = (1,0,0,0) #ore, clay,ob,geode 31 | result = 0 32 | 33 | seen = set((resource, robot)) 34 | q = deque([(resource,robot)]) 35 | round = 0 36 | while q: 37 | for _ in range(len(q)): 38 | p = q.popleft() 39 | resource, robot = p 40 | result = max(result, resource[3]) 41 | 42 | if(result > resource[3] + maxPos(robot[3], MAX-round)): 43 | continue 44 | #if(len(q) %100000 < 10 or round>=MAX): 45 | # print(id, len(q), round, len(seen), p) 46 | 47 | if round >= MAX: 48 | continue 49 | 50 | newResource = tuple([r + robot[idx] for idx,r in enumerate(resource)]) 51 | if(all([resource[i]>=types[3][i] for i in range(4)])): 52 | nnR = tuple([newResource[i] - types[3][i] for i in range(4)]) 53 | nR = tuple([robot[i] +(+1 if 3==i else 0) for i in range(4)]) 54 | v = (nnR, nR) 55 | if v not in seen: 56 | seen.add(v) 57 | q.append(v) 58 | else: 59 | v = (newResource,robot) 60 | if(v not in seen): 61 | seen.add(v) 62 | q.append(v) 63 | for idx,cost in enumerate(types): 64 | canCreate = all([resource[i]>=cost[i] for i in range(4)]) 65 | if not canCreate or idx==3: 66 | continue 67 | if(robot[idx]>limit[idx]): 68 | continue 69 | nnR = tuple([min(limit[i], newResource[i] - cost[i]) for i in range(4)]) 70 | nR = tuple([robot[i] +(1 if idx==i else 0) for i in range(4)]) 71 | v = (nnR,nR) 72 | if(v not in seen): 73 | seen.add(v) 74 | q.append(v) 75 | round = round +1 76 | return result 77 | 78 | MAX = 24 79 | 80 | bp = [convert(l.strip()) for l in sys.stdin] 81 | result = ([process(*b, MAX) for b in bp]) 82 | print(result) 83 | print(sum([r*(idx+1) for idx,r in enumerate(result)])) -------------------------------------------------------------------------------- /2022/19/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | from math import prod 4 | def maxPos(current, times): 5 | x = current 6 | y = current+times 7 | return y*(y-1)/2 - x*(x-1)/2 8 | def convert(l): 9 | p = l.split(" ") 10 | id = int(p[1][:-1]) 11 | oreOreCost= int(p[6]) 12 | clayOreCost= int(p[12]) 13 | obOreCost= int(p[18]) 14 | obClayCost= int(p[21]) 15 | GeodeOreCost= int(p[27]) 16 | GeodeObCost= int(p[30]) 17 | return (id, oreOreCost, clayOreCost, obOreCost, obClayCost, GeodeOreCost, GeodeObCost) 18 | 19 | def process(id, oreOreCost, clayOreCost, obOreCost, obClayCost, GeodeOreCost, GeodeObCost, MAX): 20 | types = [ 21 | [oreOreCost, 0,0,0], 22 | [clayOreCost, 0,0,0], 23 | [obOreCost, obClayCost,0,0], 24 | [GeodeOreCost,0,GeodeObCost,0] 25 | ] 26 | limit = [ max([types[k][i] for k in range(4)])*2 for i in range(4)] 27 | limit[3]=999999999999 28 | 29 | resource = (0,0,0,0) #ore, clay,ob,geode 30 | robot = (1,0,0,0) #ore, clay,ob,geode 31 | result = 0 32 | 33 | seen = set((resource, robot)) 34 | q = deque([(resource,robot)]) 35 | round = 0 36 | while q: 37 | for _ in range(len(q)): 38 | p = q.popleft() 39 | resource, robot = p 40 | result = max(result, resource[3]) 41 | 42 | if(result > resource[3] + maxPos(robot[3], MAX-round)): 43 | continue 44 | #if(len(q) %100000 < 10 or round>=MAX): 45 | # print(id, len(q), round, len(seen), p) 46 | 47 | if round >= MAX: 48 | continue 49 | 50 | newResource = tuple([r + robot[idx] for idx,r in enumerate(resource)]) 51 | if(all([resource[i]>=types[3][i] for i in range(4)])): 52 | nnR = tuple([newResource[i] - types[3][i] for i in range(4)]) 53 | nR = tuple([robot[i] +(+1 if 3==i else 0) for i in range(4)]) 54 | v = (nnR, nR) 55 | if v not in seen: 56 | seen.add(v) 57 | q.append(v) 58 | else: 59 | v = (newResource,robot) 60 | if(v not in seen): 61 | seen.add(v) 62 | q.append(v) 63 | for idx,cost in enumerate(types): 64 | canCreate = all([resource[i]>=cost[i] for i in range(4)]) 65 | if not canCreate or idx==3: 66 | continue 67 | if(robot[idx]>limit[idx]): 68 | continue 69 | nnR = tuple([min(limit[i], newResource[i] - cost[i]) for i in range(4)]) 70 | nR = tuple([robot[i] +(1 if idx==i else 0) for i in range(4)]) 71 | v = (nnR,nR) 72 | if(v not in seen): 73 | seen.add(v) 74 | q.append(v) 75 | round = round +1 76 | return result 77 | 78 | MAX = 32 79 | 80 | bp = [convert(l.strip()) for l in sys.stdin] 81 | result = [process(*b,MAX) for b in bp[:3]] 82 | print(result) 83 | print(prod(result)) -------------------------------------------------------------------------------- /2022/2/p1.pipe: -------------------------------------------------------------------------------- 1 | def @@input: "PAST YOUR INPUT HERE"; 2 | 3 | def modulo(x,y): 4 | --https://pipes.intelie.com/docs/0.25.2/#operator-mod 5 | --Returns the rest of the division of one number by another. 6 | ((x%y)+y)%y; 7 | 8 | def evaluate(line): 9 | def @@e: line[0]$ord - 'A':ord; 10 | def @@m: line[1]$ord - 'X':ord; 11 | ((@@m+1)+ (3,6,0)[(@@m-@@e):modulo(3)] as result, @@e as e ,@@m as m); 12 | 13 | => at the end 14 | => @for @@input:split("\n") as line 15 | => line:split(" ") as line 16 | => @set expand evaluate(line) 17 | => result:sum -------------------------------------------------------------------------------- /2022/2/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def evaluate(a,b): 4 | #elf selection 5 | e = ord(a[0]) - ord('A') 6 | #my selection 7 | m = ord(b[0]) - ord('X') 8 | # draw, win, loss 9 | points = [3,6,0] 10 | return (m+1) + points[(m-e)%3] 11 | 12 | # total points 13 | sum = 0 14 | 15 | for line in sys.stdin: 16 | a,b = line.rstrip().split(" ") 17 | sum = sum + evaluate(a,b) 18 | print(sum) 19 | 20 | -------------------------------------------------------------------------------- /2022/2/p2.pipe: -------------------------------------------------------------------------------- 1 | def @@input: "PAST YOUR INPUT HERE"; 2 | 3 | def modulo(x,y): 4 | --https://pipes.intelie.com/docs/0.25.2/#operator-mod 5 | --Returns the rest of the division of one number by another. 6 | ((x%y)+y)%y; 7 | 8 | def evaluate(line): 9 | def @@e: line[0]$ord - 'A':ord; 10 | def @@m: line[1]$ord - 'X':ord; 11 | ((0,3,6)[@@m]+ ((@@m-1+@@e):modulo(3)+1) as result, @@e as e ,@@m as m); 12 | 13 | => at the end 14 | => @for @@input:split("\n") as line 15 | => line:split(" ") as line 16 | => @set expand evaluate(line) 17 | => result:sum -------------------------------------------------------------------------------- /2022/2/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def evaluate(a,b): 4 | #elf selection 5 | # 0 R, 1 P, 2 S 6 | e = ord(a[0]) - ord('A') 7 | #should 0 lose, 1 draw, 2 win 8 | m = ord(b[0]) - ord('X') 9 | 10 | points = [0,3,6] 11 | 12 | return points[m] + ((m-1 +e )%3 +1) 13 | # 12725 14 | 15 | # total points 16 | sum = 0 17 | 18 | for line in sys.stdin: 19 | a,b = line.rstrip().split(" ") 20 | sum = sum + evaluate(a,b) 21 | print(sum) 22 | 23 | -------------------------------------------------------------------------------- /2022/20/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Node: 4 | def __init__(self, value): 5 | self.value = value 6 | self.original = None 7 | self.prev = None 8 | self.next = None 9 | def move(self, n): 10 | self.prev.next = self.next 11 | self.next.prev = self.prev 12 | for i in range(abs(self.value)%(n-1)): 13 | if(self.value>0): 14 | self.prev = self.next 15 | self.next = self.next.next 16 | else: 17 | self.next = self.prev 18 | self.prev = self.prev.prev 19 | self.prev.next = self 20 | self.next.prev = self 21 | 22 | l = [int(k) for k in sys.stdin] 23 | root = Node(l[0]) 24 | current = root 25 | for i in l[1:]: 26 | past = current 27 | current = Node(i) 28 | current.prev = past 29 | past.next = current 30 | past.original = current 31 | current.next = root 32 | root.prev = current 33 | 34 | current = root 35 | while current: 36 | current.move(len(l)) 37 | current = current.original 38 | current = root 39 | 40 | c =0 41 | k = [] 42 | while c<2: 43 | if current.value == 0: 44 | c =c+1 45 | if(c == 1): 46 | k.append(current.value) 47 | current = current.next 48 | 49 | a,b,c = k[1000%len(k)], k[2000%len(k)], k[3000%len(k)] 50 | print(a+b+c) -------------------------------------------------------------------------------- /2022/20/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Node: 4 | def __init__(self, value): 5 | self.value = value 6 | self.original = None 7 | self.prev = None 8 | self.next = None 9 | def move(self, n): 10 | self.prev.next = self.next 11 | self.next.prev = self.prev 12 | for i in range(abs(self.value)%(n-1)): 13 | if(self.value>0): 14 | self.prev = self.next 15 | self.next = self.next.next 16 | else: 17 | self.next = self.prev 18 | self.prev = self.prev.prev 19 | self.prev.next = self 20 | self.next.prev = self 21 | 22 | l = [int(k)*811589153 for k in sys.stdin] 23 | root = Node(l[0]) 24 | current = root 25 | for i in l[1:]: 26 | past = current 27 | current = Node(i) 28 | current.prev = past 29 | past.next = current 30 | past.original = current 31 | current.next = root 32 | root.prev = current 33 | 34 | for i in range(10): 35 | current = root 36 | while current: 37 | current.move(len(l)) 38 | current = current.original 39 | current = root 40 | 41 | c =0 42 | k = [] 43 | while c<2: 44 | if current.value == 0: 45 | c =c+1 46 | if(c == 1): 47 | k.append(current.value) 48 | current = current.next 49 | 50 | a,b,c = k[1000%len(k)], k[2000%len(k)], k[3000%len(k)] 51 | print(a+b+c) -------------------------------------------------------------------------------- /2022/21/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Monkey: 4 | operator = { 5 | "+": lambda x,y: x+y, 6 | "-": lambda x,y: x-y, 7 | "*": lambda x,y: x*y, 8 | "/": lambda x,y: x/y, 9 | } 10 | 11 | def __init__(self, exp): 12 | split = exp.strip().split(" ") 13 | self.a = self.op = self.b = None 14 | self.value = None 15 | if len(split)==1: 16 | self.value = int(exp) 17 | else: 18 | self.a, self.op, self.b = split 19 | def solve(self, monkeys): 20 | if self.value: 21 | return self.value 22 | 23 | a = monkeys[self.a].solve(monkeys) 24 | b = monkeys[self.b].solve(monkeys) 25 | self.value = Monkey.operator[self.op](a,b) 26 | return self.value 27 | 28 | monkeys = {} 29 | for l in sys.stdin: 30 | id, exp = l.strip().split(":") 31 | monkeys[id]=Monkey(exp) 32 | 33 | print(monkeys["root"].solve(monkeys)) -------------------------------------------------------------------------------- /2022/21/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Monkey: 4 | operator = { 5 | "+": lambda x,y: x+y, 6 | "-": lambda x,y: x-y, 7 | "*": lambda x,y: x*y, 8 | "/": lambda x,y: x/y, 9 | } 10 | 11 | operatorA = { 12 | "+": lambda x,y: x-y, 13 | "-": lambda x,y: y-x, 14 | "*": lambda x,y: x/y, 15 | "/": lambda x,y: y/x, 16 | "=": lambda x,y: y 17 | } 18 | 19 | operatorB = { 20 | "+": lambda x,y: x-y, 21 | "-": lambda x,y: x+y, 22 | "*": lambda x,y: x/y, 23 | "/": lambda x,y: x*y, 24 | "=": lambda x,y: y 25 | } 26 | def __init__(self,exp): 27 | split = exp.strip().split(" ") 28 | self.a = self.op = self.b = None 29 | self.value = None 30 | if len(split)==1: 31 | self.value = int(exp) 32 | else: 33 | self.a, self.op, self.b = split 34 | def solve(self, monkeys): 35 | if self.value: 36 | return self.value 37 | 38 | a = monkeys[self.a].solve(monkeys) 39 | b = monkeys[self.b].solve(monkeys) 40 | self.value = Monkey.operator[self.op](a,b) 41 | return self.value 42 | def solveP2(self, monkeys, expected): 43 | if self.value: 44 | return self.value 45 | if not self.a and not self.b: 46 | self.value = expected 47 | return expected 48 | try: 49 | operator = Monkey.operatorA 50 | other = self.b 51 | result = monkeys[self.a].solve(monkeys) 52 | except: 53 | operator = Monkey.operatorB 54 | other = self.a 55 | result = monkeys[self.b].solve(monkeys) 56 | 57 | expected = operator[self.op](expected,result) 58 | 59 | return monkeys[other].solveP2(monkeys, expected) 60 | 61 | monkeys = {} 62 | for l in sys.stdin: 63 | id, exp = l.strip().split(":") 64 | monkeys[id]=Monkey(exp) 65 | 66 | monkeys['humn'].value = None 67 | monkeys["root"].op = "=" 68 | print(monkeys["root"].solveP2(monkeys,0)) -------------------------------------------------------------------------------- /2022/22/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def instructions(): 4 | aux = "" 5 | for i in path: 6 | if i == 'R' or i == 'L': 7 | yield int(aux) 8 | aux = "" 9 | yield i 10 | else: 11 | aux = aux + i 12 | yield int(aux) 13 | 14 | def apply(point, ins): 15 | if not isinstance(ins, int): 16 | increment = 1 if ins == 'R' else -1 17 | return (point[0], point[1], (point[2]+increment)%4) 18 | x,y,z = point 19 | mov = movement[z] 20 | for _ in range(ins): 21 | x2,y2 = move(x,y,*mov) 22 | if(x == x2 and y==y2): 23 | break 24 | x = x2 25 | y = y2 26 | return (x,y,z) 27 | def move(x,y, dx,dy): 28 | nx = x 29 | ny = y 30 | while True: 31 | nx = (nx+dx)%rows 32 | ny = (ny+dy)%cols 33 | if(ny>= len(mat[nx])): 34 | continue 35 | v = mat[nx][ny] 36 | if v == '.': 37 | return nx,ny 38 | elif v == '#': 39 | return x,y 40 | 41 | mat = [l.replace("\n","") for l in sys.stdin] 42 | 43 | path = mat[-1:][0] 44 | 45 | mat = mat[:-2] 46 | 47 | rows = len(mat) 48 | cols = len(mat[0]) 49 | 50 | # find starting point 51 | for i in range(rows): 52 | for j in range(cols): 53 | if(mat[i][j]=='.'): 54 | x = i 55 | y = j 56 | break 57 | else: 58 | continue 59 | break 60 | 61 | RIGHT = (0,1) 62 | DOWN = (1,0) 63 | LEFT = (0,-1) 64 | UP = (-1,0) 65 | 66 | movement = [RIGHT,DOWN, LEFT, UP] 67 | point = (x,y,0) #x,y, movement index/ RIGHT 68 | 69 | for ins in instructions(): 70 | point = apply(point, ins) 71 | 72 | print(point) 73 | x,y,z = point 74 | 75 | print( 1000*(x+1) + 4*(y+1) + z) -------------------------------------------------------------------------------- /2022/23/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from math import inf 3 | from collections import defaultdict 4 | 5 | def printa(): 6 | minX = minY = inf 7 | maxX = maxY = -inf 8 | for e in elves: 9 | x,y = e 10 | minX = min(minX,x) 11 | minY = min(minY,y) 12 | maxX = max(maxX,x) 13 | maxY = max(maxY,y) 14 | print("________") 15 | for i in range(minX, maxX+1): 16 | for j in range(minY, maxY+1): 17 | c = '#' if (i,j) in elves else '.' 18 | print(c, end='') 19 | print("") 20 | print("________") 21 | return (maxX-minX+1)*(maxY-minY+1) - len(elves) 22 | 23 | 24 | elves = set() 25 | 26 | for i,l in enumerate(sys.stdin): 27 | for j,v in enumerate(l): 28 | if(v=='#'): 29 | elves.add((i,j)) 30 | printa() 31 | 32 | checks = [ 33 | lambda x,y: (x-1, y) if( (x-1,y-1) not in elves and (x-1,y) not in elves and (x-1,y+1) not in elves) else None, #north 34 | lambda x,y: (x+1, y) if( (x+1,y-1) not in elves and (x+1,y) not in elves and (x+1,y+1) not in elves) else None, #south 35 | lambda x,y: (x, y-1) if( (x-1,y-1) not in elves and (x,y-1) not in elves and (x+1,y-1) not in elves) else None, #west 36 | lambda x,y: (x, y+1) if( (x-1,y+1) not in elves and (x,y+1) not in elves and (x+1,y+1) not in elves) else None, #east 37 | lambda x,y: any([ (i,j)!=(0,0) and (x+i,y+j) in elves for i in range(-1,2) for j in range(-1,2)]) # is there any elve around? 38 | ] 39 | 40 | check = 0 41 | for i in range(10): 42 | newElves = defaultdict(set) 43 | for e in elves: 44 | if(not checks[4](*e)): 45 | newElves[e].add(e) 46 | continue 47 | for k in range(4): 48 | mov = checks[(check+k)%4](*e) 49 | if mov: 50 | newElves[mov].add(e) 51 | break 52 | else: 53 | newElves[e].add(e) 54 | aux = set() 55 | for ne, v in newElves.items(): 56 | if(len(v)==1): 57 | aux.add(ne) 58 | else: 59 | aux = aux | v 60 | elves = aux 61 | check= check+1 62 | 63 | result = printa() 64 | print(result, check) -------------------------------------------------------------------------------- /2022/23/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from math import inf 3 | from collections import defaultdict 4 | 5 | def printa(): 6 | minX = minY = inf 7 | maxX = maxY = -inf 8 | for e in elves: 9 | x,y = e 10 | minX = min(minX,x) 11 | minY = min(minY,y) 12 | maxX = max(maxX,x) 13 | maxY = max(maxY,y) 14 | print("________") 15 | for i in range(minX, maxX+1): 16 | for j in range(minY, maxY+1): 17 | c = '#' if (i,j) in elves else '.' 18 | print(c, end='') 19 | print("") 20 | print("________") 21 | return (maxX-minX+1)*(maxY-minY+1) - len(elves) 22 | 23 | 24 | elves = set() 25 | 26 | for i,l in enumerate(sys.stdin): 27 | for j,v in enumerate(l): 28 | if(v=='#'): 29 | elves.add((i,j)) 30 | 31 | 32 | checks = [ 33 | lambda x,y: (x-1, y) if( (x-1,y-1) not in elves and (x-1,y) not in elves and (x-1,y+1) not in elves) else None, #north 34 | lambda x,y: (x+1, y) if( (x+1,y-1) not in elves and (x+1,y) not in elves and (x+1,y+1) not in elves) else None, #south 35 | lambda x,y: (x, y-1) if( (x-1,y-1) not in elves and (x,y-1) not in elves and (x+1,y-1) not in elves) else None, #west 36 | lambda x,y: (x, y+1) if( (x-1,y+1) not in elves and (x,y+1) not in elves and (x+1,y+1) not in elves) else None, #east 37 | lambda x,y: any([ (i,j)!=(0,0) and (x+i,y+j) in elves for i in range(-1,2) for j in range(-1,2)]) # is there any elve around? 38 | ] 39 | 40 | check = 0 41 | while True: 42 | newElves = defaultdict(set) 43 | for e in elves: 44 | if(not checks[4](*e)): 45 | newElves[e].add(e) 46 | continue 47 | for k in range(4): 48 | mov = checks[(check+k)%4](*e) 49 | if mov: 50 | newElves[mov].add(e) 51 | break 52 | else: 53 | newElves[e].add(e) 54 | aux = set() 55 | for ne, v in newElves.items(): 56 | if(len(v)==1): 57 | aux.add(ne) 58 | else: 59 | aux = aux | v 60 | check= check+1 61 | if(elves == aux): 62 | break 63 | elves = aux 64 | 65 | 66 | result = printa() 67 | print(result, check) -------------------------------------------------------------------------------- /2022/24/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import defaultdict, deque 3 | 4 | STAY = (0,0) 5 | RIGHT = (0,1) 6 | DOWN = (1,0) 7 | LEFT = (0,-1) 8 | UP = (-1,0) 9 | moves = [STAY, RIGHT, DOWN, LEFT, UP] 10 | movesChar = { 11 | RIGHT:'>', 12 | DOWN:'v', 13 | LEFT: '<', 14 | UP: '^' 15 | } 16 | 17 | def move(px, py, mx, my): 18 | return (px+mx, py+my) 19 | 20 | def movements(pos): 21 | for m in moves: 22 | yield move(*pos, *m) 23 | 24 | def valid(x,y, next=[]): 25 | p = (x,y) 26 | if p in next: 27 | return False 28 | 29 | if p==start or p==target: 30 | return True 31 | 32 | return x>0 and x0 and y': 97 | blizzard[p].append(RIGHT) 98 | if c == '<': 99 | blizzard[p].append(LEFT) 100 | if c == '^': 101 | blizzard[p].append(UP) 102 | if c == 'v': 103 | blizzard[p].append(DOWN) 104 | 105 | result = bfs(start, target, blizzard) 106 | print(result) 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /2022/24/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import defaultdict, deque 3 | 4 | STAY = (0,0) 5 | RIGHT = (0,1) 6 | DOWN = (1,0) 7 | LEFT = (0,-1) 8 | UP = (-1,0) 9 | moves = [STAY, RIGHT, DOWN, LEFT, UP] 10 | movesChar = { 11 | RIGHT:'>', 12 | DOWN:'v', 13 | LEFT: '<', 14 | UP: '^' 15 | } 16 | 17 | def move(px, py, mx, my): 18 | return (px+mx, py+my) 19 | 20 | def movements(pos): 21 | for m in moves: 22 | yield move(*pos, *m) 23 | 24 | def valid(x,y, next=[]): 25 | p = (x,y) 26 | if p in next: 27 | return False 28 | 29 | if p==start or p==target: 30 | return True 31 | 32 | return x>0 and x0 and y': 99 | blizzard[p].append(RIGHT) 100 | if c == '<': 101 | blizzard[p].append(LEFT) 102 | if c == '^': 103 | blizzard[p].append(UP) 104 | if c == 'v': 105 | blizzard[p].append(DOWN) 106 | 107 | result, blizzard = bfs(start, target, blizzard) 108 | r2,blizzard = bfs(target, start, blizzard) 109 | r3,blizzard = bfs(start,target, blizzard) 110 | print(result+r2+r3) 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /2022/25/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | value={"=":-2, "-":-1, "0":0, "1":1,"2":2} 4 | rep = [('0',0), ('1',0), ('2',0), ('=',1), ('-',1), ('0',1)] 5 | 6 | def f(n): 7 | return sum(value[v]*5**idx for idx,v in enumerate(n[::-1])) 8 | def to(k): 9 | resp = "" 10 | rem = 0 11 | while k: 12 | c,rem = rep[k%5+rem] 13 | resp = c + resp 14 | k=k//5 15 | return resp 16 | print(to(sum([f(n.strip()) for n in sys.stdin]))) -------------------------------------------------------------------------------- /2022/3/p1.pipe: -------------------------------------------------------------------------------- 1 | def @@input: "PAST YOUR INPUT HERE"; 2 | 3 | def value(a): 4 | a>'a'? a:ord-'a':ord+1, 5 | a:ord-'A':ord+27; 6 | 7 | => at the end 8 | => @for @@input:split("\n") as line 9 | => @set line:len as len 10 | => line:substring(0,len//2) as c, line:substring(len//2) as v 11 | /* 12 | apply transformation(_$:split|>_:value:set) for each field (expand *:amap) 13 | transformation is spliting string into char seq, then converting in value and adding to a set 14 | */ 15 | => expand *:amap(_$:split|>_:value:set) 16 | => v:retain(c):get(0) as value 17 | --=> v|> map(_, sum( c:contains(_)?1,0)):itermap()|> @filter(value == 1)|> key |> :sum as value 18 | => value:sum -------------------------------------------------------------------------------- /2022/3/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def value(c): 5 | print("value of " + c ) 6 | v = ord(c) 7 | if(v>90): 8 | return v - ord('a') + 1 9 | else: 10 | return v - ord('A') + 27 11 | 12 | c = set() 13 | v = set() 14 | t = 0 15 | 16 | # reading input 17 | for line in sys.stdin: 18 | l = line.rstrip() 19 | size = len(l) 20 | for i in range(size//2): 21 | c.add(l[i]) 22 | for i in range(size//2, size): 23 | if(l[i] in c and l[i] not in v): 24 | v.add(l[i]) 25 | t = t + value(l[i]) 26 | c = set() 27 | v = set() 28 | print("") 29 | 30 | print(t) 31 | -------------------------------------------------------------------------------- /2022/3/p2.pipe: -------------------------------------------------------------------------------- 1 | def value(a): 2 | a>'a'? a:ord-'a':ord+1, 3 | a:ord-'A':ord+27; 4 | 5 | => at the end 6 | => @for @@input:split("\n") as line 7 | => line:split|>:value:set as v 8 | => set(v) as entry every 3 items 9 | => entry[0]|> @filter(entry[1]:contains(_) and entry[2]:contains(_))|>:sum as value 10 | => value:sum -------------------------------------------------------------------------------- /2022/3/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def value(c): 5 | v = ord(c) 6 | if(v>90): 7 | return v - ord('a') + 1 8 | else: 9 | return v - ord('A') + 27 10 | 11 | def convert(l): 12 | i = 0 13 | for c in l: 14 | #each letter represented from 1 to 52 15 | v = value(c) 16 | #"accumulates" the letters 17 | i = i | (1< at the end 2 | => @for @@input:split("\n") as line 3 | => expand line:regex("(?[0-9]+)-(?[0-9]+),(?[0-9]+)-(?[0-9]+)") 4 | => expand *:amap(_#) 5 | => expand ((b-a)>(d-c)? (c as a, d as b, a as c, b as d), (a,b,c,d)) --make sure (a,b)<(c,d) 6 | => (a>=c and b<=d)? 1,0 as counts 7 | => counts:sum 8 | 9 | 10 | 11 | 12 | ---------Other solution-------------- 13 | 14 | => at the end 15 | => @for @@input:split("\n") as line 16 | => expand line:regex("(?[0-9]+)-(?[0-9]+),(?[0-9]+)-(?[0-9]+)") 17 | => ((a# as s,b# as e),(c#,d#)) as p 18 | => @set p|>intervals(s,e) as intervals 19 | => intervals:len !=1? 0, (p|> intervals[0]->begin==s and intervals[0]->end==e|>:any)?1,0 as counts 20 | => counts:sum -------------------------------------------------------------------------------- /2022/4/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t = 0 4 | 5 | # reading input 6 | for line in sys.stdin: 7 | l = line.rstrip() 8 | a,b = l.split(",") 9 | a1,a2 = a.split("-") 10 | b1,b2 = b.split("-") 11 | 12 | a1 = int(a1) 13 | a2 = int(a2) 14 | b1 = int(b1) 15 | b2 = int(b2) 16 | 17 | #make sure a(b2-b1)): 19 | a1,a2,b1,b2=b1,b2,a1,a2 20 | 21 | if(a1>=b1 and a2<=b2): 22 | t = t+1 23 | 24 | print(t) -------------------------------------------------------------------------------- /2022/4/p2.pipe: -------------------------------------------------------------------------------- 1 | => at the end 2 | => @for @@input:split("\n") as line 3 | => expand line:regex("(?[0-9]+)-(?[0-9]+),(?[0-9]+)-(?[0-9]+)") 4 | => ((a# as s,b# as e),(c#,d#))|>intervals(s,e):len==1? 1,0 as counts 5 | => counts:sum -------------------------------------------------------------------------------- /2022/4/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t = 0 4 | 5 | # reading input 6 | for line in sys.stdin: 7 | l = line.rstrip() 8 | a,b = l.split(",") 9 | a1,a2 = a.split("-") 10 | b1,b2 = b.split("-") 11 | 12 | a1 = int(a1) 13 | a2 = int(a2) 14 | b1 = int(b1) 15 | b2 = int(b2) 16 | 17 | #make sure a(b2-b1)): 19 | a1,a2,b1,b2=b1,b2,a1,a2 20 | 21 | if((a1>=b1 and a1<=b2) or (a2>=b1 and a2<=b2)): 22 | t = t+1 23 | 24 | print(t) -------------------------------------------------------------------------------- /2022/5/p1.pipes: -------------------------------------------------------------------------------- 1 | def @@input: " [D] 2 | [N] [C] 3 | [Z] [M] [P] 4 | 1 2 3 5 | 6 | move 1 from 2 to 1 7 | move 3 from 1 to 3 8 | move 2 from 2 to 1 9 | move 1 from 1 to 2"; 10 | 11 | def convert(s): 12 | s:itermap()|>map(key,value:seq); 13 | 14 | def innerProcess(s,c,m,f,t): 15 | def @@cal: calc(s,c,f,t); 16 | c>=m? null, (@@cal, (@@cal, c+1,m,f,t)); 17 | 18 | def process(s,c,m): 19 | def @@rep: m[c][0]#; 20 | def @@from:m[c][1]#; 21 | def @@to:m[c][2]#; 22 | --newmap(4, (c$,@@rep, @@from,@@to):seq); 23 | (s,0, @@rep, @@from, @@to):unfold(fun (s,c,m,f,t): innerProcess(s,c,m,f,t))|>:last; 24 | 25 | def outerProcess(s,c,m): 26 | def @@p: process(s,c,m); 27 | c>=len(m)? null, (@@p, (@@p, c+1,mov)); 28 | 29 | def calc (s,c,f,t): 30 | --newmap(4, (""+f$,""+t$):seq); 31 | (s:map + newmap(t, s[f][0]+ (s[t]) ) + newmap(f, s[f]:substring(1))); 32 | 33 | => at the end 34 | => @for @@input:split("\n") as line 35 | =>@set line=="" as readingCrane 36 | => set(line) as part every (readingCrane) 37 | => @set count():overall() == 1? "crane","movement" as group 38 | => map(group, part) as m 39 | => m["crane"]|>@filter(_:contains("[")) as crane, 40 | m["movement"] as movement 41 | 42 | -- parsing input 43 | => @set (crane|>_$|> (:len:range|>((^_)[_] as a, _//4+1 as b)|>@filter(a>='A' and a<='Z')))|>@chain|>map(b, a:summary(""))as state 44 | => @set movement:seq|> _$regex("move (?[0-9]+) from (?[0-9]+) to (?[0-9]+)") as mov 45 | 46 | --executing movements 47 | => @set (state, 0, mov):unfold(fun(s,c,m): outerProcess(s,c,m)) as r 48 | --extracting response 49 | => @set r|>:last:itermap|> value[0]:summary("") as response -------------------------------------------------------------------------------- /2022/5/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque as dq 3 | 4 | 5 | #[S] [J] [S] [T] [T] [M] [D] [B] [H] 6 | # 1 2 3 4 5 6 7 8 9 7 | # 1 5 9 13 17 21 25 29 33 (chart at... => i) 8 | # crane[i//4 +1] 9 | 10 | def readCranes(cranes, l): 11 | for i, c in enumerate(l): 12 | if(c >= 'A' and c <= 'Z'): 13 | cranes[i//4 + 1].appendleft(c) 14 | 15 | 16 | def readMoves(cranes, l): 17 | p = l.split(" ") 18 | i = int(p[1]) 19 | f = int(p[3]) 20 | t = int(p[5]) 21 | for k in range(i): 22 | cranes[t].append(cranes[f].pop()) 23 | 24 | 25 | cranes = [] 26 | for i in range(10): 27 | cranes.append(dq()) 28 | 29 | mode = 0 30 | # reading input 31 | for line in sys.stdin: 32 | # reading cranes 33 | l = line.rstrip() 34 | if(mode == 1): 35 | mode = 2 36 | continue 37 | if(l[1] == '1'): 38 | mode = 1 39 | continue 40 | if mode == 0: 41 | readCranes(cranes, l) 42 | else: 43 | readMoves(cranes, l) 44 | 45 | print(cranes) 46 | for c in cranes: 47 | print(c[-1] if c else '') 48 | -------------------------------------------------------------------------------- /2022/5/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque as dq 3 | 4 | 5 | #[S] [J] [S] [T] [T] [M] [D] [B] [H] 6 | # 1 2 3 4 5 6 7 8 9 7 | # 1 5 9 13 17 21 25 29 33 (chart at... => i) 8 | # crane[i//4 +1] 9 | 10 | def readCranes(cranes, l): 11 | for i, c in enumerate(l): 12 | if(c >= 'A' and c <= 'Z'): 13 | cranes[i//4 + 1].appendleft(c) 14 | 15 | 16 | def readMoves(cranes, l): 17 | p = l.split(" ") 18 | i = int(p[1]) 19 | f = int(p[3]) 20 | t = int(p[5]) 21 | aux = dq() 22 | for k in range(i): 23 | aux.append(cranes[f].pop()) 24 | while aux: 25 | cranes[t].append(aux.pop()) 26 | 27 | 28 | cranes = [] 29 | for i in range(10): 30 | cranes.append(dq()) 31 | 32 | mode = 0 33 | # reading input 34 | for line in sys.stdin: 35 | # reading cranes 36 | l = line.rstrip() 37 | if(mode == 1): 38 | mode = 2 39 | continue 40 | if(l[1] == '1'): 41 | mode = 1 42 | continue 43 | if mode == 0: 44 | readCranes(cranes, l) 45 | else: 46 | readMoves(cranes, l) 47 | 48 | print(cranes) 49 | for c in cranes: 50 | print(c[-1] if c else '') 51 | -------------------------------------------------------------------------------- /2022/6/p1.pipes: -------------------------------------------------------------------------------- 1 | def @@input:""; 2 | 3 | def @@size: 4; 4 | def process(line, message): 5 | range(message, line:len)|>(_ as i, line:substring(_-message,_):split as chars); 6 | 7 | =>at the end 8 | =>@for @@input:split("\n") as input 9 | =>@unbatch 10 | =>@for process(input,@@size) as i 11 | => @yield 12 | =>(chars|>:set):len == @@size as a, i, chars every item 13 | =>@filter a 14 | =>firstv(i) every batch 15 | -------------------------------------------------------------------------------- /2022/6/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def solve(l,messageSize): 5 | for i in range(messageSize, len(l)): 6 | s = set(l[i-messageSize:i]) 7 | if(len(s)==messageSize): 8 | return i 9 | return 999999999999 10 | 11 | # reading input 12 | for line in sys.stdin: 13 | print(solve(line,4)) -------------------------------------------------------------------------------- /2022/6/p2.pipes: -------------------------------------------------------------------------------- 1 | def @@input:""; 2 | 3 | def @@size: 14; 4 | def process(line, message): 5 | range(message, line:len)|>(_ as i, line:substring(_-message,_):split as chars); 6 | 7 | =>at the end 8 | =>@for @@input:split("\n") as input 9 | =>@unbatch 10 | =>@for process(input,@@size) as i 11 | => @yield 12 | =>(chars|>:set):len == @@size as a, i, chars every item 13 | =>@filter a 14 | =>firstv(i) every batch 15 | -------------------------------------------------------------------------------- /2022/6/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def solve(l,messageSize): 5 | for i in range(messageSize, len(l)): 6 | s = set(l[i-messageSize:i]) 7 | if(len(s)==messageSize): 8 | return i 9 | return 999999999999 10 | 11 | # reading input 12 | for line in sys.stdin: 13 | print(solve(line,14)) -------------------------------------------------------------------------------- /2022/7/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | root = {"/":{}} 4 | 5 | c = [root] 6 | 7 | mode = 0 8 | for line in sys.stdin: 9 | l = line.rstrip().split(" ") 10 | if(l[0]=="$"): 11 | if(l[1] == "cd"): 12 | if(l[2]==".."): 13 | c.pop() 14 | else: 15 | c.append(c[-1][l[2]]) 16 | print("cd",c) 17 | elif(l[1] == "ls"): 18 | print("ls") 19 | continue 20 | else: 21 | if(l[0]=="dir"): 22 | c[-1][l[1]]={} 23 | print("add dir", c) 24 | else: 25 | c[-1][l[1]]=int(l[0]) 26 | print("add file", c) 27 | print("") 28 | 29 | count = 0 30 | 31 | def size(node): 32 | global count 33 | local = 0 34 | for k in node: 35 | print("k:",k, node[k], "is", isinstance(node[k],int)) 36 | if(isinstance(node[k], int)): 37 | local = local + node[k] 38 | else: 39 | local = local + size(node[k]) 40 | if(local<100000): 41 | count = count + local 42 | return local 43 | print(root) 44 | size(root["/"]) 45 | print(count) -------------------------------------------------------------------------------- /2022/7/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | root = {"/":{}} 4 | 5 | c = [root] 6 | 7 | mode = 0 8 | for line in sys.stdin: 9 | l = line.rstrip().split(" ") 10 | if(l[0]=="$"): 11 | if(l[1] == "cd"): 12 | if(l[2]==".."): 13 | c.pop() 14 | else: 15 | c.append(c[-1][l[2]]) 16 | print("cd",c) 17 | elif(l[1] == "ls"): 18 | print("ls") 19 | continue 20 | else: 21 | if(l[0]=="dir"): 22 | c[-1][l[1]]={} 23 | print("add dir", c) 24 | else: 25 | c[-1][l[1]]=int(l[0]) 26 | print("add file", c) 27 | print("") 28 | 29 | count = {} 30 | 31 | def size(node, path): 32 | global count 33 | local = 0 34 | for k in node: 35 | print("k:",k, node[k], "is", isinstance(node[k],int)) 36 | if(isinstance(node[k], int)): 37 | local = local + node[k] 38 | else: 39 | local = local + size(node[k], path+k+"/") 40 | count[path] = local 41 | return local 42 | print(root) 43 | size(root["/"], "/") 44 | print(count) 45 | 46 | total = 30000000-(70000000 - count["/"]) 47 | 48 | l = [i for i in count if count[i]>=total] 49 | print(l) 50 | min = 99999999999999999 51 | for i in l: 52 | if count[i]=total]) 40 | print("p1: ",p1, " p2:",p2) 41 | -------------------------------------------------------------------------------- /2022/8/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def process(i,j,mat,ref): 4 | mat[i][j]["visible"] = mat[i][j]["visible"] or mat[i][j]['v']>ref 5 | return max(mat[i][j]['v'],ref) 6 | 7 | mat = [] 8 | for line in sys.stdin: 9 | mat.append([{'v':int(i), 'visible':False} for i in line.rstrip()]) 10 | 11 | for i in range(len(mat)): 12 | a=b=c=d=-1 13 | for j in range(len(mat)): # assuming square matrix 14 | # left right 15 | a = process(i,j,mat,a) 16 | # right left 17 | b = process(i,-j-1,mat,b) 18 | # top down 19 | c = process(j,i,mat,c) 20 | # bottom up 21 | d = process(-j-1,i,mat,d) 22 | 23 | count = 0 24 | for i in range(len(mat)): 25 | for j in range(len(mat)): 26 | print(mat[i][j]['v'], "t" if mat[i][j]['visible'] else "f", end=" ") 27 | count = count + (1 if mat[i][j]['visible'] else 0) 28 | print("") 29 | 30 | print(count) -------------------------------------------------------------------------------- /2022/8/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def process(i,j,mat,a,b): 4 | c = 0 5 | s = len(mat) 6 | for k in range(1,s ): 7 | ni = i+ (a*k) 8 | nj = j + (b*k) 9 | if((ni)>=s or nj>=s or ni<0 or nj<0): 10 | break 11 | c = c +1 12 | if(mat[ni][nj]['v']>=mat[i][j]['v']): 13 | break 14 | return c 15 | mat = [] 16 | for line in sys.stdin: 17 | mat.append([{'v':int(i)} for i in line.rstrip()]) 18 | 19 | for i in range(len(mat)): 20 | for j in range(len(mat)): # assuming square matrix 21 | #down 22 | a = process(i,j,mat, 1,0) 23 | #up 24 | b = process(i,j,mat, -1,0) 25 | #right 26 | c = process(i,j,mat, 0,1) 27 | #left 28 | d = process(i,j,mat, 0,-1) 29 | mat[i][j]['k'] = a*b*c*d 30 | 31 | 32 | mmax = 0 33 | for i in range(len(mat)): 34 | for j in range(len(mat)): 35 | print(mat[i][j]['v'], mat[i][j]['k'], end=" ") 36 | mmax = max(mmax, mat[i][j]['k']) 37 | print("") 38 | 39 | print(mmax) -------------------------------------------------------------------------------- /2022/9/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def printAll(h,t): 4 | for i in range(6): 5 | for j in range(5): 6 | c = '' 7 | if( (i,j)==h): 8 | c = "H" 9 | elif (i,j)==t: 10 | c="T" 11 | else: 12 | c="." 13 | print(c, end=" ") 14 | print("") 15 | print(" ----- ") 16 | 17 | 18 | def update(h,t): 19 | i1, j1 = h 20 | i2,j2 = t 21 | if(abs(i1-i2)<2 and abs(j1-j2)<2): #touch->don't move 22 | return t 23 | if((abs(i1-i2)>0) ^ (abs(j1-j2)>0)): #move along X or Y -> move torwards H 24 | return ((i1+i2)/2, (j1+j2)/2) 25 | a = 1 if i1>i2 else -1 26 | b = 1 if j1>j2 else -1 27 | return (i2+a, j2+b) 28 | 29 | 30 | mov = { 31 | "R":(0,+1), 32 | "L":(0,-1), 33 | "D":(-1,0), 34 | "U":(1,0) 35 | } 36 | 37 | pos = set() 38 | 39 | h = (0,0) 40 | t = (0,0) 41 | 42 | pos.add(t) 43 | 44 | for l in sys.stdin: 45 | d,k = l.split(" ") 46 | for i in range(int(k)): 47 | h = (h[0]+mov[d][0], h[1]+mov[d][1]) 48 | t = update(h,t) 49 | #printAll(h,t) 50 | pos.add(t) 51 | print(len(pos)) -------------------------------------------------------------------------------- /2022/9/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def printAll(rope): 4 | for i in range(27): 5 | for j in range(27): 6 | c = '.' 7 | for k, r in enumerate(rope): 8 | if( (i,j)==r and c == '.'): 9 | c = str(k) 10 | print(c, end=" ") 11 | print("") 12 | print(" ----- ") 13 | 14 | 15 | def update(h,t): 16 | i1, j1 = h 17 | i2,j2 = t 18 | if(abs(i1-i2)<2 and abs(j1-j2)<2): #touch->don't move 19 | return t 20 | if((abs(i1-i2)>0) ^ (abs(j1-j2)>0)): #move along X or Y -> move torwards H 21 | return ((i1+i2)/2, (j1+j2)/2) 22 | a = 1 if i1>i2 else -1 23 | b = 1 if j1>j2 else -1 24 | return (i2+a, j2+b) 25 | 26 | 27 | mov = { 28 | "R":(0,+1), 29 | "L":(0,-1), 30 | "D":(-1,0), 31 | "U":(1,0) 32 | } 33 | 34 | pos = set() 35 | 36 | rope = [(0,0) for i in range(10)] 37 | 38 | pos.add(rope[0]) 39 | 40 | for l in sys.stdin: 41 | d,k = l.split(" ") 42 | for i in range(int(k)): 43 | rope[0] = (rope[0][0]+mov[d][0], rope[0][1]+mov[d][1]) 44 | for r in range(1,len(rope)): 45 | rope[r] = update(rope[r-1], rope[r]) 46 | #printAll(rope) 47 | pos.add(rope[-1]) 48 | print(len(pos)) -------------------------------------------------------------------------------- /2023/01/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | 5 | sum=0 6 | 7 | for line in sys.stdin: 8 | line = line.rstrip() 9 | a = b = -1 10 | l = len(line) 11 | for i in range(l): 12 | if a == -1 and line[i].isnumeric(): 13 | a = int(line[i]) 14 | 15 | if b == -1 and line[l-i-1].isnumeric(): 16 | b = int(line[l-i-1]) 17 | sum = sum + 10*a + b 18 | print(sum) 19 | -------------------------------------------------------------------------------- /2023/01/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | names = ["one","two","three","four","five","six","seven","eight","nine"] 5 | firstLetters = set(["o","t","f","s","e","n"]) 6 | def parse(s): 7 | if s[0].isnumeric(): 8 | return int(s[0]) 9 | if s[0] not in firstLetters: 10 | return -1 11 | for idx,name in enumerate(names): 12 | if s.startswith(name): 13 | return idx+1 14 | return -1 15 | 16 | sum=0 17 | 18 | for line in sys.stdin: 19 | line = line.rstrip() 20 | a = b = -1 21 | l = len(line) 22 | for i in range(l): 23 | if a == -1: 24 | a = parse(line[i:]) 25 | 26 | if b == -1: 27 | b = parse(line[l-i-1:]) 28 | sum = sum + 10*a + b 29 | print(sum) 30 | -------------------------------------------------------------------------------- /2023/02/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | maxV = { 4 | "r":12, 5 | "g": 13, 6 | "b": 14 7 | } 8 | 9 | def possible(l): 10 | for w in l.split(","): 11 | count, color = w.strip().split(" ") 12 | count = int(count) 13 | if count > maxV[color[0]]: 14 | return False 15 | return True 16 | sum=0 17 | 18 | for line in sys.stdin: 19 | line = line.strip() 20 | game, x = line.split(':') 21 | game = int(game[5:]) 22 | result = all([possible(k.strip()) for k in x.split(";")]) 23 | sum = sum + (game if result else 0) 24 | print(sum) -------------------------------------------------------------------------------- /2023/02/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | 5 | def possible(l): 6 | maxV = { 7 | "r":0, 8 | "g": 0, 9 | "b": 0 10 | } 11 | for w in l.split(","): 12 | count, color = w.strip().split(" ") 13 | count = int(count) 14 | color = color[0] 15 | maxV[color] = max(maxV[color], count) 16 | return maxV 17 | sum=0 18 | 19 | for line in sys.stdin: 20 | line = line.strip() 21 | game, x = line.split(':') 22 | game = int(game[5:]) 23 | result = [possible(k.strip()) for k in x.split(";")] 24 | r=g=b=0 25 | for i in result: 26 | r = max(r, i['r']) 27 | g = max(g, i['g']) 28 | b = max(b, i['b']) 29 | sum = sum + (r*g*b) 30 | print(sum) -------------------------------------------------------------------------------- /2023/03/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def neighbors(x,y): 4 | for i in [-1,0,1]: 5 | a = x+i 6 | if a<0 or a>=len(mat): 7 | continue 8 | for j in [-1,0,1]: 9 | b = y+j 10 | if b<0 or b>=len(mat[a]): 11 | continue 12 | if i == 0 and j == 0: 13 | continue 14 | yield mat[a][b] 15 | def isValidChar(c): 16 | return c!='.' and (ord(c)-ord('0')<0 or ord(c)-ord('9')>0) 17 | 18 | def isValidPos(old, i,j): 19 | if old: 20 | return old 21 | return any([isValidChar(c) for c in neighbors(i,j)]) 22 | 23 | mat = [l.strip() for l in sys.stdin] 24 | #print(mat) 25 | 26 | num = False 27 | valid = False 28 | 29 | acc = [] 30 | den = [] 31 | 32 | current = 0 33 | for i, l in enumerate(mat): 34 | for j, c in enumerate(l): 35 | if num: 36 | if c.isnumeric(): 37 | current = current*10 + int(c) 38 | valid = isValidPos(valid, i, j) 39 | else: 40 | if valid: 41 | acc.append(current) 42 | else: 43 | den.append(current) 44 | num = False 45 | valid = False 46 | else: 47 | if c.isnumeric(): 48 | num = True 49 | current = int(c) 50 | valid = isValidPos(valid, i, j) 51 | #print(i, l, j, c) 52 | print(sum(acc)) 53 | #print(den) -------------------------------------------------------------------------------- /2023/03/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | 4 | def neighbors(x,y): 5 | for i in [-1,0,1]: 6 | a = x+i 7 | if a<0 or a>=len(mat): 8 | continue 9 | for j in [-1,0,1]: 10 | b = y+j 11 | if b<0 or b>=len(mat[a]): 12 | continue 13 | if i == 0 and j == 0: 14 | continue 15 | yield (mat[a][b], a,b) 16 | 17 | 18 | def findStar(stars, i,j): 19 | for n, i2,j2 in neighbors(i,j): 20 | if n=='*': 21 | stars.add((i2,j2)) 22 | return stars 23 | mat = [l.strip() for l in sys.stdin] 24 | #print(mat) 25 | 26 | num = False 27 | 28 | stars = set() 29 | acc = [] 30 | den = [] 31 | result = {} 32 | 33 | current = 0 34 | for i, l in enumerate(mat): 35 | for j, c in enumerate(l): 36 | if num: 37 | if c.isnumeric(): 38 | current = current*10 + int(c) 39 | stars = findStar(stars, i, j) 40 | else: 41 | for x,y in stars: 42 | if x not in result: 43 | result[x]={} 44 | if y not in result[x]: 45 | result[x][y]=[] 46 | result[x][y].append(current) 47 | num = False 48 | stars = set() 49 | else: 50 | if c.isnumeric(): 51 | num = True 52 | current = int(c) 53 | stars = findStar(stars, i, j) 54 | finalResult=0 55 | for i in result: 56 | for j in result[i]: 57 | v = result[i][j] 58 | size = len(v) 59 | if size==2: 60 | finalResult = finalResult + math.prod(v) 61 | print(finalResult) -------------------------------------------------------------------------------- /2023/04/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | sum = 0 5 | for line in sys.stdin: 6 | cards = line.strip().split(": ")[1].split(" | ") 7 | win = set(cards[0].split(" ")) 8 | if '' in win: 9 | win.remove('') 10 | mine = set(cards[1].split(" ")) 11 | points = len(win.intersection(mine))-1 12 | sum = sum +( 2**points if points>=0 else 0) 13 | print(sum) -------------------------------------------------------------------------------- /2023/04/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | c = [1]*200 5 | for i,line in enumerate(sys.stdin): 6 | cards = line.strip().split(": ")[1].split(" | ") 7 | win = set(cards[0].split(" ")) 8 | if '' in win: 9 | win.remove('') 10 | mine = set(cards[1].split(" ")) 11 | points = len(win.intersection(mine)) 12 | for j in range(points): 13 | c[j+i+1] = c[j+i+1] + c[i] 14 | 15 | print(sum(c[:i+1])) -------------------------------------------------------------------------------- /2023/05/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | lines = [l.strip() for l in sys.stdin] 5 | 6 | current = [int(x) for x in lines[0][7:].split(" ")] 7 | nxt = [] 8 | i = 2 9 | for line in lines[2:]: 10 | #print(line, current, nxt) 11 | if len(line) ==0: 12 | current = nxt+current 13 | nxt = [] 14 | continue 15 | 16 | if ':' in line: 17 | continue 18 | dstart, sstart, size = [int(x.strip()) for x in line.split(" ")] 19 | #print(sstart, dstart, size) 20 | aux = [] 21 | for v in current: 22 | if v>=sstart and v=send): 37 | aux.append((a,b)) 38 | continue 39 | # Before with intersec 40 | # ..... 41 | # ...... 42 | if (a=send): 50 | aux.append((a,send-1)) 51 | nxt.append((send+diff, b+diff)) 52 | continue 53 | # within 54 | # ...... 55 | # ............ 56 | if (a>=sstart and b=send): 63 | aux.append((a,sstart-1)) 64 | aux.append((send,b)) 65 | nxt.append((sstart+diff, send+diff)) 66 | continue 67 | 68 | print(sstart, send, a,b) 69 | raise Exception("dunno ") 70 | current = aux 71 | 72 | 73 | current = nxt+current 74 | print(min(current)[0]) -------------------------------------------------------------------------------- /2023/06/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | 4 | lines = [l.split(":")[1].strip() for l in sys.stdin] 5 | time = [int(x) for x in lines[0].split()] 6 | distance = [int(x) for x in lines[1].split()] 7 | 8 | result = 1 9 | for i in range(len(time)): 10 | b = time[i] 11 | c = distance[i] 12 | 13 | delta = math.sqrt(b*b -4*c) 14 | 15 | minR = math.floor(((b-delta)/2) +1) 16 | maxR = math.ceil(((b+delta)/2)-1) 17 | diff = maxR-minR+1 18 | #print(b,c,delta, minR, maxR, diff) 19 | result = result * diff 20 | print(result) -------------------------------------------------------------------------------- /2023/06/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | 4 | lines = [l.split(":")[1].strip() for l in sys.stdin] 5 | time = [int(lines[0].replace(" ", ""))] 6 | distance = [int(lines[1].replace(" ", ""))] 7 | 8 | result = 1 9 | 10 | for i in range(len(time)): 11 | b = time[i] 12 | c = distance[i] 13 | 14 | delta = math.sqrt(b*b -4*c) 15 | 16 | minR = math.floor(((b-delta)/2) +1) 17 | maxR = math.ceil(((b+delta)/2)-1) 18 | diff = maxR-minR+1 19 | #print(b,c,delta, minR, maxR, diff) 20 | result = result * diff 21 | print(result) -------------------------------------------------------------------------------- /2023/07/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from functools import cmp_to_key 3 | from collections import defaultdict 4 | 5 | ref = 'AKQJT98765432' 6 | 7 | def extractInfo(a): 8 | mmax = 0 9 | c = defaultdict(int) 10 | for k in a: 11 | c[k] = c[k]+1 12 | mmax = max(mmax, c[k]) 13 | return (mmax, sum([1 if v==2 else 0 for (k,v) in c.items()])) 14 | 15 | def hands_cmp(a,b): 16 | maxA, pairsA = extractInfo(a[0]) 17 | maxB, pairsB = extractInfo(b[0]) 18 | if maxA != maxB: 19 | return maxA-maxB 20 | 21 | if pairsA != pairsB: 22 | return pairsA - pairsB 23 | 24 | for i in range(5): 25 | A = a[0][i] 26 | B = b[0][i] 27 | if A == B: 28 | continue 29 | return ref.find(B) - ref.find(A) 30 | return 0 31 | 32 | hands_cmp_key = cmp_to_key(hands_cmp) 33 | 34 | hands = [l.strip().split() for l in sys.stdin] 35 | hands.sort(key=hands_cmp_key) 36 | result = 0 37 | i = 1 38 | for k,v in hands: 39 | result = result + i*int(v) 40 | i = i+1 41 | print(result) 42 | -------------------------------------------------------------------------------- /2023/07/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from functools import cmp_to_key 3 | from collections import defaultdict 4 | 5 | ref = 'AKQT98765432J' 6 | 7 | def isFullHouse(mmax, a,c): 8 | if mmax != 3: 9 | return False 10 | if 'J' in a: 11 | fullHouse = True 12 | for k,v in c.items(): 13 | if k == 'J': 14 | continue 15 | fullHouse = fullHouse and v == 2 16 | return fullHouse 17 | return 2 in c.values() and 3 in c.values() 18 | def extractInfo(a): 19 | mmax = 0 20 | c = defaultdict(int) 21 | for k in a: 22 | c[k] = c[k]+1 23 | if(k == 'J'): 24 | continue 25 | mmax = max(mmax, c[k]) 26 | mmax = mmax + c['J'] 27 | 28 | fullHouse = isFullHouse(mmax, a, c) 29 | if fullHouse: 30 | return 3.5 31 | pairs = sum([1 if v==2 else 0 for v in c.values()]) 32 | if c['J'] == 2: 33 | pairs = pairs -1 34 | if mmax == 2 and pairs ==0: 35 | pairs = 1 36 | if pairs == 2: 37 | mmax = 2.5 38 | return mmax 39 | 40 | def hands_cmp(a,b): 41 | maxA = extractInfo(a[0]) 42 | maxB = extractInfo(b[0]) 43 | if maxA != maxB: 44 | return maxA-maxB 45 | 46 | for i in range(5): 47 | A = a[0][i] 48 | B = b[0][i] 49 | if A == B: 50 | continue 51 | return ref.find(B) - ref.find(A) 52 | return 0 53 | 54 | hands_cmp_key = cmp_to_key(hands_cmp) 55 | hands = [l.strip().split() for l in sys.stdin] 56 | hands.sort(key=hands_cmp_key) 57 | result = 0 58 | i = 1 59 | for k,v in hands: 60 | result = result + i*int(v) 61 | i = i+1 62 | print(result) 63 | 64 | -------------------------------------------------------------------------------- /2023/08/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = [l.strip() for l in sys.stdin] 4 | 5 | ins = input[0] 6 | 7 | graph = {} 8 | 9 | for i in input[2:]: 10 | source, aux = i.split(" = ") 11 | l,r = aux[1:-1].split(", ") 12 | graph[source] = (l,r) 13 | 14 | node = 'AAA' 15 | i = 0 16 | count = 0 17 | while node != 'ZZZ': 18 | node = graph[node][0 if ins[i]=='L' else 1] 19 | i = (i +1)%len(ins) 20 | count = count +1 21 | print(count) -------------------------------------------------------------------------------- /2023/08/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from math import lcm 3 | 4 | input = [l.strip() for l in sys.stdin] 5 | 6 | ins = input[0] 7 | 8 | graph = {} 9 | 10 | nodes = set() 11 | for i in input[2:]: 12 | source, aux = i.split(" = ") 13 | l,r = aux[1:-1].split(", ") 14 | graph[source] = (l,r) 15 | if source.endswith('A'): 16 | nodes.add(source) 17 | 18 | 19 | def size(node): 20 | i = 0 21 | count = 0 22 | while not node.endswith('Z'): 23 | node = graph[node][0 if ins[i]=='L' else 1] 24 | i = (i +1)%len(ins) 25 | count = count +1 26 | return count 27 | 28 | 29 | cycles = [] 30 | for n in nodes: 31 | print(n) 32 | cycles.append(size(n)) 33 | print(cycles) 34 | print(lcm(*cycles)) -------------------------------------------------------------------------------- /2023/09/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def nextNumber(n): 4 | if len(n) == 0: 5 | return 0 6 | k = [n[i+1]-n[i] for i in range(len(n)-1)] 7 | return n[-1]+ nextNumber(k) 8 | 9 | 10 | input = [l.strip() for l in sys.stdin] 11 | 12 | total = 0 13 | for i in input: 14 | numbers = [int(x) for x in i.split()] 15 | next = nextNumber(numbers) 16 | total = total + next 17 | print(total) -------------------------------------------------------------------------------- /2023/09/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def nextNumber(n): 4 | if len(n) == 0: 5 | return 0 6 | k = [n[i+1]-n[i] for i in range(len(n)-1)] 7 | return n[0] - nextNumber(k) 8 | 9 | 10 | input = [l.strip() for l in sys.stdin] 11 | 12 | total = 0 13 | for i in input: 14 | numbers = [int(x) for x in i.split()] 15 | next = nextNumber(numbers) 16 | total = total + next 17 | print(total) -------------------------------------------------------------------------------- /2023/10/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from math import ceil 3 | from collections import deque 4 | 5 | mat = [l.strip() for l in sys.stdin] 6 | 7 | dir = { 8 | '|':[(-1,0), (1,0)], 9 | '-':[(0,-1), (0,1)], 10 | 'L':[(-1,0), (0,1)], 11 | 'J':[(-1,0), (0,-1)], 12 | '7':[(1,0), (0,-1)], 13 | 'F':[(1,0), (0,1)], 14 | 'S':[(-1,0),(0,-1),(0,1),(1,0)], 15 | '.':[], 16 | } 17 | 18 | def neighbors(x,y): 19 | for i,j in dir[mat[x][y]]: 20 | a = i + x 21 | b = j + y 22 | if a<0 or a>=len(mat): 23 | continue 24 | if b<0 or b>=len(mat[a]): 25 | continue 26 | if mat[a][b] == '.': 27 | continue 28 | yield (a,b) 29 | def next (c,p): 30 | for n in neighbors(*c): 31 | if n == p: 32 | continue 33 | return n 34 | 35 | start = (0,0) 36 | for i, l in enumerate(mat): 37 | for j, c in enumerate(l): 38 | if c == 'S': 39 | start = (i,j) 40 | 41 | c = start 42 | prev = start 43 | depth = 0 44 | while c == prev or c!=start: 45 | n = next(c,prev) 46 | print(c, prev, n) 47 | prev, c = c, n 48 | depth = depth + 1 49 | 50 | print(*start, depth, depth//2) -------------------------------------------------------------------------------- /2023/10/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from math import ceil 3 | from collections import deque 4 | 5 | mat = [[*l.strip()] for l in sys.stdin] 6 | 7 | dir = { 8 | '|':[(-1,0), (1,0)], 9 | '-':[(0,-1), (0,1)], 10 | 'L':[(-1,0), (0,1)], 11 | 'J':[(-1,0), (0,-1)], 12 | '7':[(1,0), (0,-1)], 13 | 'F':[(1,0), (0,1)], 14 | 'S':[(-1,0),(0,-1),(0,1),(1,0)], 15 | '.':[], 16 | } 17 | 18 | def neighbors(x,y, flood = False): 19 | opt = dir[mat[x][y]] if not flood else dir['S'] 20 | for i,j in opt: 21 | a = i + x 22 | b = j + y 23 | if a<0 or a>=len(mat): 24 | continue 25 | if b<0 or b>=len(mat[a]): 26 | continue 27 | dot = mat[a][b] == '.' 28 | if flood != dot: 29 | continue 30 | yield (a,b) 31 | 32 | 33 | def flood(start): 34 | q = deque([start]) #queue 35 | round = 0 36 | s = set() #seen 37 | while q: 38 | for _ in range(len(q)): #all in this depth 39 | p = q.popleft() 40 | 41 | if mat[p[0]][p[1]] != '.': 42 | continue 43 | mat[p[0]][p[1]] = '@' 44 | 45 | for u in neighbors(*p, True): 46 | if u not in s: 47 | s.add(u) 48 | q.append(u) 49 | round = round+1 50 | return round 51 | def next (c,p): 52 | for n in neighbors(*c): 53 | if c == p and c not in neighbors(*n): 54 | # start and we are not sure what direction to take 55 | continue 56 | if n == p: 57 | continue 58 | return n 59 | 60 | start = (0,0) 61 | for i, l in enumerate(mat): 62 | for j, c in enumerate(l): 63 | if c == 'S': 64 | start = (i,j) 65 | 66 | 67 | cycle = set() 68 | c = start 69 | prev = start 70 | depth = 0 71 | while c == prev or c!=start: 72 | cycle.add(c) 73 | n = next(c,prev) 74 | #print(c, prev, n) 75 | prev, c = c, n 76 | depth = depth + 1 77 | 78 | # clear junk 79 | for i, l in enumerate(mat): 80 | for j, c in enumerate(l): 81 | if (i,j) in cycle: 82 | continue 83 | mat[i][j] = '.' 84 | #print(''.join(l)) 85 | #print("") 86 | 87 | 88 | for i in range(len(mat)): 89 | flood((i,0)) 90 | flood((i, len(mat[i])-1)) 91 | 92 | ''' 93 | for i, l in enumerate(mat): 94 | print(''.join(l)) 95 | 96 | print("") 97 | ''' 98 | 99 | count = 0 100 | for i, l in enumerate(mat): 101 | out = True 102 | semi = '' 103 | for j, c in enumerate(l): 104 | if not out and c == '.': 105 | count= count +1 106 | mat[i][j]='$' 107 | if c == '|' or (c == semi or (len(semi)>0 and c =='S')): 108 | out = not out 109 | if c == 'L': 110 | semi = '7' 111 | elif c == 'F': 112 | semi = 'J' 113 | elif c != '-': 114 | semi = '' 115 | q = (2 if out else 0) + (1 if len(semi)>0 else 0) 116 | #print(c, q, end = '') 117 | #print("") 118 | 119 | ''' 120 | for i, l in enumerate(mat): 121 | print(''.join(l)) 122 | 123 | ''' 124 | print(count) -------------------------------------------------------------------------------- /2023/11/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | def addLines(mat): 5 | size = len(mat) 6 | nm = [] 7 | for i in range(size): 8 | r = True 9 | for j in range(size): 10 | r = r and mat[i][j] != '#' 11 | nm.append(mat[i]) 12 | if r: 13 | nm.append(['.' for _ in range(size)]) 14 | return nm 15 | def addColumn(mat): 16 | size = len(mat) 17 | nm=[] 18 | for i in range(size): 19 | nm.append([]) 20 | for i in range(len(mat[0])): 21 | c = True 22 | for j in range(size): 23 | c = c and mat[j][i] != '#' 24 | nm[j].append(mat[j][i]) 25 | if c: 26 | for j in range(size): 27 | nm[j].append('.') 28 | return nm 29 | def findPoints(mat): 30 | p = [] 31 | for i, l in enumerate(mat): 32 | for j, c in enumerate(l): 33 | if c == '#': 34 | p.append((i,j)) 35 | return p 36 | 37 | 38 | mat = [[*l.strip()] for l in sys.stdin] 39 | mat = addLines(mat) 40 | mat = addColumn(mat) 41 | points = findPoints(mat) 42 | 43 | dists = [] 44 | 45 | 46 | for i in range(len(points)): 47 | p1 = points[i] 48 | for j in range(i+1, len(points)): 49 | p2 = points[j] 50 | x = abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) 51 | dists.append(x) 52 | print(sum(dists)) -------------------------------------------------------------------------------- /2023/11/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | def empty(mat): 5 | size = len(mat) 6 | er = set() 7 | ec = set() 8 | 9 | for i in range(size): 10 | r = True 11 | c = True 12 | for j in range(size): 13 | r = r and mat[i][j] != '#' 14 | c = c and mat[j][i] != '#' 15 | if r: 16 | er.add(i) 17 | if c: 18 | ec.add(i) 19 | return er,ec 20 | 21 | def findPoints(mat): 22 | p = [] 23 | for i, l in enumerate(mat): 24 | for j, c in enumerate(l): 25 | if c == '#': 26 | p.append((i,j)) 27 | return p 28 | 29 | 30 | mat = [[*l.strip()] for l in sys.stdin] 31 | el, ec = empty(mat) 32 | points = findPoints(mat) 33 | dists = [] 34 | weight = 1000000 35 | 36 | 37 | for i in range(len(points)): 38 | p1 = points[i] 39 | for j in range(i+1, len(points)): 40 | p2 = points[j] 41 | x = 0 42 | for k in range(min(p1[0], p2[0]), max(p1[0], p2[0])): 43 | x = x + (weight if k in el else 1) 44 | 45 | for k in range(min(p1[1], p2[1]), max(p1[1], p2[1])): 46 | x = x + (weight if k in ec else 1) 47 | 48 | dists.append(x) 49 | print(sum(dists)) 50 | -------------------------------------------------------------------------------- /2023/12/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | 5 | cases = [l.strip().split() for l in sys.stdin] 6 | 7 | def valid(line, expected): 8 | current =0 9 | actual = [] 10 | for c in line: 11 | if (c == '.' or c == '?') and current>0: 12 | actual.append(current) 13 | current = 0 14 | if c == '#': 15 | current = current +1 16 | if current>0: 17 | actual.append(current) 18 | return actual ==expected 19 | 20 | def back(line, expected): 21 | if '?' not in line: 22 | return 1 if valid(line, expected) else 0 23 | i = line.index('?') 24 | line[i] = '#' 25 | a = back(line, expected) 26 | line[i] = '.' 27 | b = back(line, expected) 28 | line[i] = '?' 29 | return a+b 30 | 31 | 32 | 33 | result = 0 34 | for i in cases: 35 | line = [*i[0]] 36 | expected = [ int(x) for x in i[1].split(',')] 37 | count = back(line, expected) 38 | #print(line, expected, count) 39 | result = result + count 40 | print(result) 41 | -------------------------------------------------------------------------------- /2023/12/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | 5 | cases = [l.strip().split() for l in sys.stdin] 6 | 7 | def points(line): 8 | current =0 9 | actual = [] 10 | for c in line: 11 | if c == '.' and current>0: 12 | actual.append(current) 13 | current = 0 14 | if c == '#': 15 | current = current +1 16 | if current>0: 17 | actual.append(current) 18 | return actual 19 | 20 | def simplify(line): 21 | 22 | ## .....#.... == .#. 23 | # #....# == #.# 24 | s = [] 25 | prev = '' 26 | for i,c in enumerate(line): 27 | skip = c =='.' and prev == '.' 28 | prev = c 29 | if skip: 30 | continue 31 | s.append(c) 32 | return s 33 | 34 | 35 | mem={} 36 | def back(l, k): 37 | l = simplify(l) 38 | s = "".join(l) 39 | if s not in mem: 40 | mem[s] = doBack(l,k) 41 | return mem[s] 42 | 43 | 44 | 45 | def doBack(line, expected): 46 | if '?' not in line: 47 | p = points(line) 48 | if p == expected: 49 | #print("right", "".join(line), expected) 50 | return 1 51 | else: 52 | return 0 53 | 54 | i = line.index('?') 55 | p = points(line[:i]) 56 | 57 | if p[:-1] != expected[:max(0,len(p)-1)] or (len(p)>0 and p[-1]> expected[min(max(len(p)-1, 0), len(expected)-1)]): 58 | #print("prune", "".join(line), "\n",p[:-1], expected[:max(0,len(p)-1)]) 59 | return 0 60 | line[i] = '#' 61 | a = back(simplify(line), expected) 62 | line[i] = '.' 63 | b = back(simplify(line), expected) 64 | line[i] = '?' 65 | return a+b 66 | 67 | 68 | 69 | result = 0 70 | for idx, i in enumerate(cases): 71 | mem = {} 72 | line = [*'?'.join([i[0]]*5)] 73 | expected = [ int(x) for x in i[1].split(',')]*5 74 | #print("".join(line), expected) 75 | count = back(line, expected) 76 | #print("".join(line), expected, count) 77 | result = result + count 78 | 79 | print(result) 80 | -------------------------------------------------------------------------------- /2023/14/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | mat = [[*l.strip()] for l in sys.stdin] 4 | 5 | for i, l in enumerate(mat): 6 | print(i,l) 7 | for j, c in enumerate(l): 8 | if c == 'O': 9 | k = i-1 10 | while k>=0: 11 | w = mat[k][j] 12 | if w == '#' or w =='O': 13 | k = k +1 14 | break 15 | k = k-1 16 | k = max(k,0) 17 | mat[i][j]='.' 18 | mat[k][j]='O' 19 | print("") 20 | total = 0 21 | for i, l in enumerate(mat): 22 | p = len(l)-i 23 | print(p,l) 24 | for c in l: 25 | if c == 'O': 26 | total = total + p 27 | print(total) -------------------------------------------------------------------------------- /2023/14/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def points(mat, rowSize): 4 | total = 0 5 | for i in range(rowSize): 6 | p = rowSize-i 7 | for j in range(rowSize): 8 | c = mat[i*rowSize + j] 9 | if c == 'O': 10 | total = total + p 11 | return total 12 | 13 | def tiltV(mat, dx): 14 | if dx>0: 15 | mat.reverse() 16 | for i, l in enumerate(mat): 17 | for j, c in enumerate(l): 18 | if c == 'O': 19 | k = i-1 20 | while k>=0: 21 | w = mat[k][j] 22 | if w == '#' or w =='O': 23 | k = k +1 24 | break 25 | k = k-1 26 | k = max(k,0) 27 | mat[i][j]='.' 28 | mat[k][j]='O' 29 | 30 | if dx>0: 31 | mat.reverse() 32 | return mat 33 | 34 | def tiltH(mat, dy): 35 | for i, l in enumerate(mat): 36 | if dy>0: 37 | l.reverse() 38 | for j, c in enumerate(l): 39 | if c == 'O': 40 | k = j-1 41 | while k>=0: 42 | w = mat[i][k] 43 | if w == '#' or w =='O': 44 | k = k +1 45 | break 46 | k = k-1 47 | k = max(k,0) 48 | mat[i][j]='.' 49 | mat[i][k]='O' 50 | if dy>0: 51 | l.reverse() 52 | return mat 53 | def cycle(mat): 54 | mat = tiltV(mat, -1) 55 | mat = tiltH(mat, -1) 56 | mat = tiltV(mat, 1) 57 | mat = tiltH(mat, 1) 58 | return mat 59 | 60 | def process(mat, target): 61 | hist = [] 62 | i = 0 63 | while i < target: 64 | i = i +1 65 | mat = cycle(mat) 66 | 67 | mnow = "".join(["".join(q) for q in mat]) 68 | if(mnow in hist): 69 | first = hist.index(mnow) 70 | c = i-first 71 | f = (target - first)%c+first 72 | return hist[f-1] 73 | hist.append(mnow) 74 | return "".join(["".join(q) for q in mat]) 75 | 76 | mat = [[*l.strip()] for l in sys.stdin] 77 | rowSize = len(mat) 78 | mat = process(mat, 1000000000) 79 | total = points(mat, rowSize) 80 | print(total) -------------------------------------------------------------------------------- /2023/15/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | lines = [l.strip().split(",") for l in sys.stdin] 4 | 5 | 6 | total = 0 7 | for p in lines[0]: 8 | local = 0 9 | for c in p: 10 | local = ((local + ord(c))*17)%256 11 | total = total + local 12 | print(total) -------------------------------------------------------------------------------- /2023/15/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def hash(p): 4 | local = 0 5 | for c in p: 6 | local = ((local + ord(c))*17)%256 7 | return local 8 | 9 | def remove(m, bucket, key): 10 | if bucket not in m: 11 | return 12 | b = m[bucket] 13 | n = [] 14 | for k,v in b: 15 | if k == key: 16 | continue 17 | n.append((k,v)) 18 | m[bucket]=n 19 | 20 | def upsert(m, bucket, key, value): 21 | if bucket not in m: 22 | m[bucket] = [] 23 | b = m[bucket] 24 | n = [] 25 | add = False 26 | for k,v in b: 27 | if k == key: 28 | n.append((k,value)) 29 | add = True 30 | else: 31 | n.append((k,v)) 32 | if not add: 33 | n.append((key,value)) 34 | m[bucket]=n 35 | 36 | lines = [l.strip().split(",") for l in sys.stdin] 37 | 38 | m = {} 39 | 40 | 41 | for p in lines[0]: 42 | if '-' == p[-1]: 43 | key = p[:-1] 44 | bucket = hash(key) 45 | remove(m, bucket, key) 46 | else: 47 | key,value = p.split("=") 48 | bucket = hash(key) 49 | upsert(m, bucket, key, value) 50 | 51 | total = 0 52 | for k, v in m.items(): 53 | for i,x in enumerate(v): 54 | total = total + (k+1)*(i+1)*int(x[1]) 55 | print(total) -------------------------------------------------------------------------------- /2023/16/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | lines = [[*l.strip()] for l in sys.stdin] 4 | 5 | print(lines) 6 | 7 | RIGHT = (0, 1) 8 | DOWN = (1, 0) 9 | LEFT = (0, -1) 10 | UP = (-1, 0) 11 | 12 | movement = [RIGHT, DOWN, LEFT, UP] 13 | 14 | m = [] 15 | for i in range(len(lines)): 16 | k = [] 17 | m.append(k) 18 | for _ in range(len(lines[i])): 19 | k.append(0) 20 | 21 | 22 | def bfs(g,v,m): #graph, value 23 | s = {v} #seen 24 | q = deque([v]) #queue 25 | while q: 26 | p = q.popleft() 27 | x,y,d = p 28 | print(x,y,d, len(q)) 29 | if not(x<0 or y<0 or x>=(len(g)) or y>=(len(g[x]))): 30 | m[x][y]=m[x][y]+1 31 | a = x + d[0] 32 | b = y + d[1] 33 | if a<0 or b<0 or a>=(len(g)) or b>=(len(g[a])): 34 | continue 35 | c = g[a][b] 36 | u = [] 37 | if c == '.': 38 | u.append((a,b,d)) 39 | if c == '|': 40 | if d == DOWN or d == UP: 41 | u.append((a,b,d)) 42 | else: 43 | u.append((a,b,DOWN)) 44 | u.append((a,b,UP)) 45 | if c == '-': 46 | if d == DOWN or d == UP: 47 | u.append((a,b,LEFT)) 48 | u.append((a,b,RIGHT)) 49 | else: 50 | u.append((a,b,d)) 51 | if c == '\\': 52 | if d == DOWN: 53 | u.append((a,b,RIGHT)) 54 | if d == LEFT: 55 | u.append((a,b,UP)) 56 | if d == UP: 57 | u.append((a,b,LEFT)) 58 | if d == RIGHT: 59 | u.append((a,b,DOWN)) 60 | if c == '/': 61 | if d == DOWN: 62 | u.append((a,b,LEFT)) 63 | if d == LEFT: 64 | u.append((a,b,DOWN)) 65 | if d == UP: 66 | u.append((a,b,RIGHT)) 67 | if d == RIGHT: 68 | u.append((a,b,UP)) 69 | 70 | for t in u: 71 | if t not in s: 72 | s.add(t) 73 | q.append(t) 74 | 75 | 76 | bfs(lines, (0,-1, RIGHT), m) 77 | total = 0 78 | for i in m: 79 | total = total + sum([min(k,1) for k in i]) 80 | for c in i: 81 | print(c, end="") 82 | print("") 83 | print(total) -------------------------------------------------------------------------------- /2023/16/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | lines = [[*l.strip()] for l in sys.stdin] 4 | 5 | RIGHT = (0, 1) 6 | DOWN = (1, 0) 7 | LEFT = (0, -1) 8 | UP = (-1, 0) 9 | 10 | movement = [RIGHT, DOWN, LEFT, UP] 11 | 12 | 13 | def bfs(g,v,m): #graph, value 14 | s = {v} #seen 15 | q = deque([v]) #queue 16 | while q: 17 | p = q.popleft() 18 | x,y,d = p 19 | if not(x<0 or y<0 or x>=(len(g)) or y>=(len(g[x]))): 20 | m[x][y]=m[x][y]+1 21 | a = x + d[0] 22 | b = y + d[1] 23 | if a<0 or b<0 or a>=(len(g)) or b>=(len(g[a])): 24 | continue 25 | c = g[a][b] 26 | u = [] 27 | if c == '.': 28 | u.append((a,b,d)) 29 | if c == '|': 30 | if d == DOWN or d == UP: 31 | u.append((a,b,d)) 32 | else: 33 | u.append((a,b,DOWN)) 34 | u.append((a,b,UP)) 35 | if c == '-': 36 | if d == DOWN or d == UP: 37 | u.append((a,b,LEFT)) 38 | u.append((a,b,RIGHT)) 39 | else: 40 | u.append((a,b,d)) 41 | if c == '\\': 42 | if d == DOWN: 43 | u.append((a,b,RIGHT)) 44 | if d == LEFT: 45 | u.append((a,b,UP)) 46 | if d == UP: 47 | u.append((a,b,LEFT)) 48 | if d == RIGHT: 49 | u.append((a,b,DOWN)) 50 | if c == '/': 51 | if d == DOWN: 52 | u.append((a,b,LEFT)) 53 | if d == LEFT: 54 | u.append((a,b,DOWN)) 55 | if d == UP: 56 | u.append((a,b,RIGHT)) 57 | if d == RIGHT: 58 | u.append((a,b,UP)) 59 | 60 | for t in u: 61 | if t not in s: 62 | s.add(t) 63 | q.append(t) 64 | 65 | 66 | def count(lines, start): 67 | m = [] 68 | for i in range(len(lines)): 69 | k = [] 70 | m.append(k) 71 | for _ in range(len(lines[i])): 72 | k.append(0) 73 | bfs(lines, start, m) 74 | total = 0 75 | for i in m: 76 | total = total + sum([min(k,1) for k in i]) 77 | # for c in i: 78 | # print(c, end="") 79 | # print("") 80 | #print(total) 81 | return total 82 | result =0 83 | end = len(lines) 84 | for i in range(end): 85 | result = max(result,count(lines, (i,-1, RIGHT))) 86 | result = max(result,count(lines, (i,end, LEFT))) 87 | result = max(result,count(lines, (-1,i, DOWN))) 88 | result = max(result,count(lines, (end,i, UP))) 89 | print(result) -------------------------------------------------------------------------------- /2023/17/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from heapq import heappush, heappop 3 | 4 | lines = [[*l.strip()] for l in sys.stdin] 5 | 6 | RIGHT = (0, 1) 7 | DOWN = (1, 0) 8 | LEFT = (0, -1) 9 | UP = (-1, 0) 10 | 11 | movement = [RIGHT, DOWN, LEFT, UP] 12 | def valid(x,y): 13 | return not(x<0 or y<0 or x>=(len(lines)) or y>=(len(lines[x]))) 14 | def neig(x,y,d): 15 | if d == RIGHT or d==LEFT: 16 | yield DOWN 17 | yield UP 18 | elif d == DOWN or d==UP: 19 | yield RIGHT 20 | yield LEFT 21 | else: #start 22 | yield RIGHT 23 | yield DOWN 24 | 25 | def dfs(g, mmin, mmax): 26 | p = (0,0) 27 | t = (len(g)-1, len(g[0])-1) 28 | heap = [(0, (0,0), (0,0))] 29 | hmap = {(0,0):0} 30 | s = set() #seen 31 | while heap: 32 | cost, p, d = heappop(heap) 33 | 34 | if p==t: 35 | return cost 36 | if (p, d) in s: 37 | continue 38 | s.add((p,d)) 39 | 40 | x,y = p 41 | for nd in neig(x,y,d): 42 | nc = cost 43 | dx,dy = nd 44 | for i in range(1, mmax+1): 45 | np = (x+i*dx, y+i*dy) 46 | if not valid(*np): 47 | continue 48 | nc = nc + int(g[np[0]][np[1]]) 49 | if i>=mmin: 50 | u = (np, (dx,dy)) 51 | if hmap.get(u, 999999999999999)<=nc: 52 | continue 53 | hmap[u]=nc 54 | heappush(heap, (nc, np, nd)) 55 | return cost 56 | 57 | 58 | print(lines) 59 | print(dfs(lines, 0,3)) -------------------------------------------------------------------------------- /2023/17/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from heapq import heappush, heappop 3 | 4 | lines = [[*l.strip()] for l in sys.stdin] 5 | 6 | RIGHT = (0, 1) 7 | DOWN = (1, 0) 8 | LEFT = (0, -1) 9 | UP = (-1, 0) 10 | 11 | movement = [RIGHT, DOWN, LEFT, UP] 12 | def valid(x,y): 13 | return not(x<0 or y<0 or x>=(len(lines)) or y>=(len(lines[x]))) 14 | def neig(x,y,d): 15 | if d == RIGHT or d==LEFT: 16 | yield DOWN 17 | yield UP 18 | elif d == DOWN or d==UP: 19 | yield RIGHT 20 | yield LEFT 21 | else: #start 22 | yield RIGHT 23 | yield DOWN 24 | 25 | def dfs(g, mmin, mmax): 26 | p = (0,0) 27 | t = (len(g)-1, len(g[0])-1) 28 | heap = [(0, (0,0), (0,0))] 29 | hmap = {(0,0):0} 30 | s = set() #seen 31 | while heap: 32 | cost, p, d = heappop(heap) 33 | 34 | if p==t: 35 | return cost 36 | if (p, d) in s: 37 | continue 38 | s.add((p,d)) 39 | 40 | x,y = p 41 | for nd in neig(x,y,d): 42 | nc = cost 43 | dx,dy = nd 44 | for i in range(1, mmax+1): 45 | np = (x+i*dx, y+i*dy) 46 | if not valid(*np): 47 | continue 48 | nc = nc + int(g[np[0]][np[1]]) 49 | if i>=mmin: 50 | u = (np, (dx,dy)) 51 | if hmap.get(u, 999999999999999)<=nc: 52 | continue 53 | hmap[u]=nc 54 | heappush(heap, (nc, np, nd)) 55 | return cost 56 | 57 | 58 | print(lines) 59 | print(dfs(lines, 4,10)) -------------------------------------------------------------------------------- /2023/18/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | def neighbors(mat, x,y, minx, maxx, miny, maxy): 5 | opt = [(-1,0),(0,-1),(0,1),(1,0)] 6 | for i,j in opt: 7 | a = i + x 8 | b = j + y 9 | if a<0 or a>=len(mat) or a=maxx: 10 | continue 11 | if b<0 or b>=len(mat[a])or b=maxy: 12 | continue 13 | yield (a,b) 14 | 15 | 16 | def flood(mat, start, minx, maxx, miny, maxy): 17 | q = deque([start]) #queue 18 | round = 0 19 | s = set() #seen 20 | while q: 21 | for _ in range(len(q)): #all in this depth 22 | 23 | p = q.popleft() 24 | if mat[p[0]][p[1]] != 0: 25 | continue 26 | mat[p[0]][p[1]] = 1 27 | 28 | for u in neighbors(mat, *p, minx, maxx, miny, maxy): 29 | if u not in s: 30 | s.add(u) 31 | q.append(u) 32 | 33 | lines = [[x for x in l.strip().split()] for l in sys.stdin] 34 | 35 | size = 1000 36 | start = 500 37 | 38 | mat = [[0 for col in range(size)] for row in range(size)] 39 | 40 | x = start 41 | y = start 42 | 43 | minx =x 44 | miny = y 45 | maxx=x 46 | maxy=y 47 | for d,s,c in lines: 48 | #print(d, int(s), c) 49 | for i in range(int(s)): 50 | if d == 'R': 51 | y = y+1 52 | if d == 'L': 53 | y = y-1 54 | if d == 'U': 55 | x = x-1 56 | if d == 'D': 57 | x = x+1 58 | mat[x][y]=mat[x][y]-1 59 | minx = min(x, minx) 60 | miny = min(y, miny) 61 | maxx = max(x, maxx) 62 | maxy = max(y, maxy) 63 | ''' 64 | print(minx, maxx, miny, maxy) 65 | for i in range(minx-1, maxx+2): 66 | for j in range(miny-1, maxy+2): 67 | print( "." if mat[i][j] == 0 else "#", end=" ") 68 | print("") 69 | ''' 70 | flood(mat, (minx-1,miny-1), minx-2, maxx+2, miny-2, maxy+2) 71 | 72 | ''' 73 | for i in range(minx-1, maxx+2): 74 | for j in range(miny-1, maxy+2): 75 | print( "." if mat[i][j] <= 0 else "#", end=" ") 76 | print("") 77 | ''' 78 | count = 0 79 | for i in range(minx-1, maxx+2): 80 | for j in range(miny-1, maxy+2): 81 | if mat[i][j]<=0: 82 | count = count +1 83 | print(count) -------------------------------------------------------------------------------- /2023/19/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | import json 4 | 5 | def parse(line): 6 | pkg = {} 7 | for x in line.strip()[1:-1].split(","): 8 | n, v=x.split("=") 9 | pkg[n]=int(v) 10 | return pkg 11 | def evaluate(rule, pkg): 12 | for r in rule: 13 | if len(r) == 1: 14 | return r[0] 15 | r,dst = r 16 | item = r[0] 17 | op = r[1] 18 | threshold = int(r[2:]) 19 | value = pkg[item] 20 | if op == '<' and value' and value>threshold: 23 | return dst 24 | 25 | 26 | def proc(rules, pkg): 27 | s = 'in' 28 | while s != 'A' and s!='R': 29 | s = evaluate(rules[s], pkg) 30 | return 0 if s=='R' else sum(pkg.values()) 31 | 32 | 33 | rules={} 34 | for l in sys.stdin: 35 | if len(l.strip()) == 0: 36 | break 37 | name, rule = l.split("{") 38 | rule = rule.strip()[:-1].split(",") 39 | rule = [r.split(":") for r in rule] 40 | rules[name]=rule 41 | 42 | total = 0 43 | for l in sys.stdin: 44 | pkg = parse(l) 45 | total += proc(rules, pkg) 46 | print(total) 47 | -------------------------------------------------------------------------------- /2023/23/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import heapq as hq 3 | 4 | dir = { 5 | '#':[], 6 | '>':[(0,1)], 7 | '<':[(0,-1)], 8 | '^':[(-1,0)], 9 | 'v':[(1,0)], 10 | '.': [(-1,0), (0,-1), (0,1), (1,0)] 11 | } 12 | 13 | def neighbors(g,x,y): 14 | c = g[x][y] 15 | for i,j in dir[c]: 16 | a = x+i 17 | if a<0 or a>=len(g): 18 | continue 19 | b = y+j 20 | if b<0 or b>=len(g[a]): 21 | continue 22 | if i == 0 and j == 0: 23 | continue 24 | c = g[a][b] 25 | if c == '#': 26 | continue 27 | yield (a,b) 28 | 29 | 30 | def dfs(g,v,t): #graph, value, targets 31 | dist = {v:0} 32 | s = {(str(v))} #seen 33 | q = [] #heap 34 | hq.heappush(q,(1,[v])) 35 | mp = [] 36 | while q: 37 | size,path = hq.heappop(q) 38 | print(len(q), size, len(s)) 39 | p = path[-1] 40 | if p in dist and sizedist[t]: 44 | mp = path 45 | continue 46 | for u in neighbors(g,*p): 47 | if u in path: 48 | continue 49 | npath = "".join([str(x) for x in path]) + str(u) 50 | if npath not in s: 51 | s.add(npath) 52 | hq.heappush(q, (size+1,path+[u])) 53 | return dist[t],mp 54 | 55 | 56 | mat = [[*l.strip()] for l in sys.stdin] 57 | 58 | d, mp= dfs(mat, (0,1), (len(mat)-1, len(mat)-2)) 59 | 60 | print(d-1) 61 | 62 | ''' 63 | for i,l in enumerate(mat): 64 | for j,c in enumerate(l): 65 | if (i,j) in mp: 66 | c = 'O' 67 | print(c, end="") 68 | print("") 69 | ''' 70 | -------------------------------------------------------------------------------- /2023/24/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def valid (a,b, minV, maxV): 5 | #print("comparing",a,b) 6 | sx1,sy1,sz1 = a[0] 7 | dx1,dy1,dz1 = a[1] 8 | 9 | sx2,sy2,sz2 = b[0] 10 | dx2,dy2,dz2 = b[1] 11 | 12 | num = dx1*dx2*(sy2-sy1)+ (dx2*sx1*dy1) - (dx1*sx2*dy2) 13 | 14 | div = dx2*dy1 - dx1*dy2 15 | if div==0: 16 | #print("parallel") 17 | return False 18 | x = num / div 19 | t1 = (x-sx1)/dx1 20 | t2 = (x-sx2)/dx2 21 | y = sy1+dy1*t1 22 | if t1<0 and t2<0: 23 | #print("in the past for both") 24 | return False 25 | if t1<0: 26 | #print("in the past for A") 27 | return False 28 | if t2<0: 29 | #print("in the past for B") 30 | return False 31 | 32 | #print(x,y) 33 | return x>=minV and x<=maxV and y>=minV and y<=maxV 34 | 35 | entries = [] 36 | for l in sys.stdin: 37 | a, b = l.strip().split(" @ ") 38 | convert = lambda x: [ int(y) for y in x.replace(",", "").split()] 39 | entries.append((convert(a), convert(b))) 40 | 41 | #print(entries) 42 | count = 0 43 | for i in range(len(entries)): 44 | for j in range(i+1, len(entries)): 45 | if i == j: 46 | continue 47 | cross = valid(entries[i],entries[j],200000000000000,400000000000000) 48 | if(cross): 49 | count+=1 50 | #print(cross) 51 | #print(" ") 52 | print(count) -------------------------------------------------------------------------------- /2023/24/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | #https://semath.info/src/inverse-cofactor-ex4.html 3 | 4 | def createMat(rows, cols): 5 | return [[0 for _ in range(cols)] for _ in range(rows)] 6 | 7 | def createSub(mat, ignoreI, ignoreJ): 8 | #ideally this would not copy the data 🤷 9 | nmat = [] 10 | for i in range(len(mat)): 11 | if i == ignoreI: 12 | continue 13 | nmat.append([]) 14 | for j in range(len(mat[i])): 15 | if j == ignoreJ: 16 | continue 17 | nmat[-1].append(mat[i][j]) 18 | return nmat 19 | 20 | 21 | def scalarProd(factor, mat): 22 | for i in range(len(mat)): 23 | for j in range(len(mat[i])): 24 | mat[i][j]*=factor 25 | return mat 26 | 27 | def det(mat): 28 | #assuming it is sizeXsize 29 | size = len(mat) 30 | if size == 2: 31 | return mat[0][0]*mat[1][1] - mat[0][1]*mat[1][0] 32 | 33 | factor = 1 34 | result =0 35 | for i in range(size): 36 | result+= factor * mat[i][0] * det(createSub(mat, i,0)) 37 | factor*=-1 38 | return result 39 | 40 | def adjugate(mat): 41 | size = len(mat) 42 | result = createMat(size,size) 43 | for i in range(size): 44 | for j in range(size): 45 | factor = 1 if (i+j)%2==0 else -1 46 | #this is not a typo, for Aij = factor * det(Mji) 47 | result[i][j] = factor * det(createSub(mat, j,i)) 48 | return result 49 | 50 | def inverse(mat): 51 | #https://semath.info/src/inverse-cofactor-ex4.html 52 | d = det(mat) 53 | #print(d) 54 | factor = 1/d 55 | #print(factor) 56 | adj = adjugate(mat) 57 | #printa(adj) 58 | return scalarProd(factor, adj) 59 | 60 | def prod(a,b): 61 | if(len(a[0])!=len(b)): 62 | raise Exception("cannot multiply mat %dX%d with mat %dX%d"%(len(a),len(a[0]), len(b), len(b[0]))) 63 | rows = len(a) 64 | cols = len(b[0]) 65 | c = createMat(rows, cols) 66 | common = len(b) 67 | for i in range(rows): 68 | for j in range(cols): 69 | for k in range(common): 70 | c[i][j]+=a[i][k]*b[k][j] 71 | return c 72 | 73 | 74 | entries = [] 75 | for l in sys.stdin: 76 | a, b = l.strip().split(" @ ") 77 | convert = lambda x: [ int(y) for y in x.replace(",", "").split()] 78 | # sx,sy,sz | dx,dy,dz 79 | entries.append((convert(a), convert(b))) 80 | 81 | # consider that each hailstone is going towards the desired point 82 | # so each sx,sy,sz | dx,dy,dz becomes sx-a,sy-b,sz-c | dx-d,dy-e,dz-f 83 | # since we know that at some point they should colide, we can use x=0, y=0, z=0 to create some equations 84 | # (sx-a) + (dx-d)T = 0 85 | # (sy-b) + (dy-e)T = 0 86 | # (sz-c) + (dz-f)T = 0 => can be ignored 87 | # using the first two we have: 88 | # (sx-a)/(dx-d) = (sy-b)/(dy-e) => (sx-a)(dy-e) -(dx-d)*(sy-b) = 0 (I) 89 | # Choose two entries (sx1,sy1,sz1 | dx1,dy1,dz1) and (sx2,sy2,sz2 | dx2,dy2,dz2) 90 | # and do (I1)-(I2) and after some manipulation you get: 91 | # (dy2 - dy1)*a + (dx1-dx2)*b + (sy1-sy2)*d + (sx2-sx1)*e = (dx1*sy1 - dx2*sy2 + sx2*dy2 -sx1*dy1) 92 | # so... α*a + β*b + γ*d + δ*e = ε 93 | # using 4 equations like this (4 combinations of entries) we can have: 94 | # so... [[α0,β0,γ0,δ0],[α1,β1,γ1,δ1],[α2,β2,γ2,δ2],[α3,β3,γ3,δ3]] * [[a],[b],[d],[e]] = [[ε0],[ε1],[ε2],[ε3]] 95 | # we can write it as A*x=b => x = A^-1 *B 96 | 97 | A = [] 98 | B = [] 99 | 100 | for j in range(1,5) : 101 | [[sx1,sy1,sz1],[dx1,dy1,dz1 ]] = entries[0] 102 | [[sx2,sy2,sz2],[dx2,dy2,dz2 ]] = entries[j] 103 | 104 | A.append([(dy2-dy1), (dx1-dx2), (sy1-sy2), (sx2-sx1)]) 105 | B.append([(dx1*sy1 - dx2*sy2 + sx2*dy2 -sx1*dy1)]) 106 | AI = inverse(A) 107 | X = prod(AI, B) 108 | [[a],[b],[d],[e]] = X 109 | 110 | [[sx1,sy1,sz1],[dx1,dy1,dz1 ]] = entries[0] 111 | [[sx2,sy2,sz2],[dx2,dy2,dz2 ]] = entries[1] 112 | 113 | t1 = (a - sx1) / (dx1 - d) 114 | t2 = (a - sx2) / (dx2 - d) 115 | 116 | f = ((sz1 - sz2) + t1 * dz1 - t2 * dz2) / (t1 - t2) 117 | c = sz1 + t1 * (dz1 - f) 118 | 119 | print(a + b + c) -------------------------------------------------------------------------------- /2023/25/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def outboundLen(g,s, v): 4 | return len(g[v]-s) 5 | def outboundEdges(g,s): 6 | total = 0 7 | for v in s: 8 | total+= outboundLen(g,s,v) 9 | return total 10 | def maxOutboundConnected(g,s): 11 | resp = next(iter(s)) 12 | for i in s: 13 | if outboundLen(g,s,i)>outboundLen(g,s,resp): 14 | resp = i 15 | return resp 16 | 17 | g ={} 18 | for l in sys.stdin: 19 | v,e = l.split(':') 20 | e = set(e.split()) 21 | for i in e: 22 | if i not in g: 23 | g[i] = set() 24 | g[i].add(v) 25 | if v not in g: 26 | g[v] = set() 27 | g[v].add(i) 28 | 29 | s = set(g) 30 | while outboundEdges(g, s) != 3: 31 | s.remove(maxOutboundConnected(g,s)) 32 | print(len(s) * len(set(g)-s)) -------------------------------------------------------------------------------- /2024/01/p1.exs: -------------------------------------------------------------------------------- 1 | defmodule P do 2 | def x(s) do 3 | s |> Enum.map(&String.to_integer/1) 4 | end 5 | 6 | def y([h | t]) do 7 | [a, b] = h 8 | [tA, tB] = y(t) 9 | [[a | tA], [b | tB]] 10 | end 11 | 12 | def y([]) do 13 | [[], []] 14 | end 15 | 16 | def calc([[], []]) do 17 | 0 18 | end 19 | 20 | def calc([[a | ta], [b | tb]]) do 21 | abs(a - b) + calc([ta, tb]) 22 | end 23 | end 24 | 25 | IO.read(:stdio, :eof) 26 | |> String.split("\n") 27 | |> Enum.map(fn x -> String.split(x, " ") end) 28 | |> Enum.reject(fn x -> x == [""] end) 29 | |> Enum.map(&P.x/1) 30 | |> P.y() 31 | |> Enum.map(&Enum.sort/1) 32 | # |> IO.inspect 33 | |> P.calc() 34 | |> IO.inspect() 35 | -------------------------------------------------------------------------------- /2024/01/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | a=[] 4 | b=[] 5 | for l in sys.stdin: 6 | l = l.rstrip() 7 | x,y = l.split() 8 | a.append(int(x)) 9 | b.append(int(y)) 10 | a.sort() 11 | b.sort() 12 | sum=0 13 | for x,y in zip(a,b): 14 | sum = sum + abs(x-y) 15 | print(sum) 16 | -------------------------------------------------------------------------------- /2024/01/p2.exs: -------------------------------------------------------------------------------- 1 | defmodule P do 2 | def x(s) do 3 | s |> Enum.map(&String.to_integer/1) 4 | end 5 | 6 | def y([h | t]) do 7 | [a, b] = h 8 | [tA, tB] = y(t) 9 | [[a | tA], [b | tB]] 10 | end 11 | 12 | def y([]) do 13 | [[], []] 14 | end 15 | 16 | 17 | def calc([a, b]) do 18 | freq = Enum.frequencies(b) 19 | 20 | a 21 | |> Enum.map(fn x -> Map.get(freq, x, 0) * x end) 22 | |> Enum.sum() 23 | end 24 | end 25 | 26 | IO.read(:stdio, :eof) 27 | |> String.split("\n") 28 | |> Enum.map(fn x -> String.split(x, " ") end) 29 | |> Enum.reject(fn x -> x == [""] end) 30 | |> Enum.map(&P.x/1) 31 | |> P.y() 32 | |> Enum.map(&Enum.sort/1) 33 | # |> IO.inspect 34 | |> P.calc() 35 | |> IO.inspect() 36 | -------------------------------------------------------------------------------- /2024/01/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | a=[] 4 | b={} 5 | for l in sys.stdin: 6 | l = l.rstrip() 7 | x,y = l.split() 8 | a.append(int(x)) 9 | y=int(y) 10 | b[y]=1 if y not in b else 1+b[y] 11 | 12 | sum=0 13 | for x in a: 14 | sum = sum + (x * (b[x] if x in b else 0)) 15 | print(sum) 16 | -------------------------------------------------------------------------------- /2024/02/p1.exs: -------------------------------------------------------------------------------- 1 | defmodule P02 do 2 | def parse(s) do 3 | s 4 | |> String.split(" ", trim: true) 5 | |> Enum.map(&String.to_integer/1) 6 | end 7 | 8 | def diff(y) do 9 | y 10 | |> Enum.chunk_every(2, 1, :discard) 11 | |> Enum.map(fn [x, y] -> x - y end) 12 | |> Enum.into(MapSet.new) 13 | end 14 | 15 | def valid(y) do 16 | x= diff(y) 17 | # |> IO.inspect 18 | safe(x, MapSet.new([1,2,3])) or safe(x, MapSet.new([-1,-2,-3])) 19 | end 20 | 21 | def safe(x,y) do 22 | MapSet.size(MapSet.difference(x,y)) ==0 23 | end 24 | 25 | 26 | def calc(y) do 27 | valid(y) 28 | end 29 | end 30 | 31 | x = IO.read(:stdio, :eof) 32 | |> String.split("\n", trim: true) 33 | #|> IO.inspect() 34 | |> Enum.map(&P02.parse/1) 35 | |> Enum.map(&P02.calc/1) 36 | #|> IO.inspect() 37 | 38 | 39 | IO.inspect(Enum.count(x, & &1)) 40 | -------------------------------------------------------------------------------- /2024/02/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def safe(s): 4 | return len(s.difference({-1,-2,-3})) == 0 or len(s.difference({1,2,3}))==0 5 | 6 | result = 0 7 | for l in sys.stdin: 8 | v = [int(x) for x in l.split()] 9 | diff = set([v[i+1]-v[i] for i in range(len(v)-1)]) 10 | if(safe(diff)): 11 | result +=1 12 | print(result) 13 | -------------------------------------------------------------------------------- /2024/02/p2.exs: -------------------------------------------------------------------------------- 1 | defmodule P02 do 2 | def parse(s) do 3 | s 4 | |> String.split(" ", trim: true) 5 | |> Enum.map(&String.to_integer/1) 6 | end 7 | 8 | def diff(y) do 9 | #IO.inspect(y) 10 | y 11 | |> Enum.chunk_every(2, 1, :discard) 12 | |> Enum.map(fn [x, y] -> x - y end) 13 | |> Enum.into(MapSet.new) 14 | end 15 | 16 | def valid(y) do 17 | x= diff(y) 18 | # |> IO.inspect 19 | safe(x, MapSet.new([1,2,3])) or safe(x, MapSet.new([-1,-2,-3])) 20 | end 21 | 22 | def safe(x,y) do 23 | MapSet.size(MapSet.difference(x,y)) ==0 24 | end 25 | def validWithSkip(y, -1) do 26 | valid(y) or validWithSkip(y, 0) 27 | end 28 | 29 | def validWithSkip(y, n) do 30 | if n>=length(y) do 31 | false 32 | else 33 | valid(Enum.concat(Enum.slice(y,0, n),Enum.slice(y, (n+1)..length(y)))) or validWithSkip(y, n+1) 34 | end 35 | end 36 | 37 | def calc(y) do 38 | validWithSkip(y, -1) 39 | end 40 | end 41 | 42 | x = IO.read(:stdio, :eof) 43 | |> String.split("\n", trim: true) 44 | #|> IO.inspect() 45 | |> Enum.map(&P02.parse/1) 46 | |> Enum.map(&P02.calc/1) 47 | #|> IO.inspect() 48 | 49 | 50 | IO.inspect(Enum.count(x, & &1)) 51 | -------------------------------------------------------------------------------- /2024/02/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def safe(s): 4 | return len(s.difference({-1,-2,-3})) == 0 or len(s.difference({1,2,3}))==0 5 | 6 | def process(x, skip=None): 7 | v = x[:skip]+x[skip+1:] if skip != None else x 8 | diff = set([v[i+1]-v[i] for i in range(len(v)-1)]) 9 | return safe(diff) 10 | 11 | result = 0 12 | for l in sys.stdin: 13 | v = [int(x) for x in l.split()] 14 | valid=process(v) 15 | i = 0 16 | while i IO.inspect 5 | |> Enum.map(fn [_, a, b] -> String.to_integer(a) * String.to_integer(b) end) 6 | # |> IO.inspect 7 | |> Enum.sum() 8 | end 9 | end 10 | 11 | IO.read(:stdio, :eof) 12 | |> P03.calc() 13 | |> IO.inspect() 14 | -------------------------------------------------------------------------------- /2024/03/p1.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | 4 | reg = "mul\(([0-9]{1,3}),([0-9]{1,3})\)" 5 | 6 | sum = 0 7 | for line in sys.stdin: 8 | for x,y in re.findall(reg, line): 9 | sum += int(x)*int(y) 10 | print(sum) 11 | -------------------------------------------------------------------------------- /2024/03/p2.exs: -------------------------------------------------------------------------------- 1 | defmodule P03 do 2 | def calc(input) do 3 | Regex.scan(~r/mul\(([0-9]{1,3}),([0-9]{1,3})\)|do\(\)|don\'t\(\)/, input, []) 4 | |> Enum.reduce([0, true], fn x, [sum, enabled] -> 5 | case [x, enabled] do 6 | [["don't()"], _] -> [sum, false] 7 | [["do()"], _] -> [sum, true] 8 | [_, false] -> [sum, enabled] 9 | [[_, a, b], true] -> [sum + String.to_integer(a) * String.to_integer(b), enabled] 10 | end 11 | end) 12 | |> hd 13 | end 14 | end 15 | 16 | IO.read(:stdio, :eof) 17 | |> P03.calc() 18 | |> IO.inspect() 19 | -------------------------------------------------------------------------------- /2024/03/p2.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | 4 | def calc(s): 5 | reg = "mul\(([0-9]{1,3}),([0-9]{1,3})\)" 6 | sum = 0 7 | for x,y in re.findall(reg, s): 8 | sum += int(x)*int(y) 9 | return sum 10 | 11 | 12 | sum = 0 13 | line = "".join([l for l in sys.stdin]) 14 | split = line.split("don't()") 15 | #start enabled 16 | sum+=calc(split[0]) 17 | for t in range(1,len(split)): 18 | s2 = split[t].split("do()", 1) 19 | #discard everything before "do()" 20 | if len(s2)>1: 21 | sum+=calc(s2[1]) 22 | print(sum) 23 | -------------------------------------------------------------------------------- /2024/04/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | alternatives = [ 4 | (-1,-1), 5 | (-1,0), 6 | (-1,1), 7 | (0,-1), 8 | (0,1), 9 | (1,0), 10 | (1,-1), 11 | (1,1) 12 | ] 13 | 14 | def look(i,j,mat, delta, wish): 15 | #print("look", i,j,delta, wish) 16 | if len(wish)==0: 17 | #print("true len") 18 | return True 19 | if i<0 or i>=len(mat): 20 | #print('i') 21 | return False 22 | if j<0 or j>=len(mat[i]): 23 | #print('j') 24 | return False 25 | if mat[i][j]!=wish[0]: 26 | #print('wish', wish, mat[i][j]) 27 | return False 28 | return look(i+delta[0], j+delta[1], mat, delta, wish[1:]) 29 | 30 | def test(i,j,mat): 31 | count=0 32 | for d in alternatives: 33 | if look(i,j,mat,d, ['X','M','A','S']): 34 | count+=1 35 | return count 36 | 37 | 38 | mat = [l.strip() for l in sys.stdin] 39 | print(mat) 40 | count = 0 41 | for i in range(len(mat)): 42 | for j in range(len(mat[i])): 43 | if mat[i][j]=='X': 44 | count+=test(i,j,mat) 45 | print(count) 46 | 47 | -------------------------------------------------------------------------------- /2024/04/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | alternatives = [ 5 | (-1,-1), 6 | (-1,0), 7 | (-1,1), 8 | (0,-1), 9 | (0,1), 10 | (1,0), 11 | (1,-1), 12 | (1,1) 13 | ] 14 | 15 | def look(i,j,mat,wish): 16 | #print("look", i,j,delta, wish) 17 | if len(wish)==0: 18 | #print("true len") 19 | return True 20 | if i<0 or i>=len(mat): 21 | #print('i') 22 | return False 23 | if j<0 or j>=len(mat[i]): 24 | #print('j') 25 | return False 26 | if mat[i][j]!=wish[0]: 27 | #print('wish', wish, mat[i][j]) 28 | return False 29 | return True 30 | 31 | def diag(i,j,a,b,mat): 32 | return look(i+a[0], j+a[1], mat, "M") and look(i+b[0], j+b[1], mat, "S") 33 | 34 | def test(i,j,mat): 35 | if (diag(i,j,(-1,-1),(+1,+1), mat) or diag(i,j,(+1,+1),(-1,-1),mat)) and (diag(i,j,(-1,+1), (+1,-1), mat) or diag(i,j, (+1,-1), (-1,+1),mat)): 36 | return 1 37 | return 0 38 | 39 | mat = [l.strip() for l in sys.stdin] 40 | #print(mat) 41 | count = 0 42 | for i in range(len(mat)): 43 | for j in range(len(mat[i])): 44 | if mat[i][j]=='A': 45 | count+=test(i,j,mat) 46 | print(count) 47 | 48 | -------------------------------------------------------------------------------- /2024/05/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def process(nums, rule): 4 | read = set() 5 | for n in nums: 6 | if n in rule and len(rule[n].intersection(read))>0: 7 | return 0 8 | read.add(n) 9 | return nums[len(nums)//2] 10 | 11 | 12 | rule = {} 13 | for l in sys.stdin: 14 | if len(l.strip())==0: 15 | break 16 | a,b = [int(x) for x in l.strip().split("|")] 17 | if a not in rule: 18 | rule[a]=set() 19 | rule[a].add(b) 20 | 21 | sum = 0 22 | for l in sys.stdin: 23 | nums= [int(x) for x in l.strip().split(",")] 24 | sum+=process(nums, rule) 25 | print(sum) 26 | -------------------------------------------------------------------------------- /2024/05/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def findInvalid(nums,i, rule): 4 | v = nums[i] 5 | if v not in rule: 6 | return -1 7 | for j in range(i): 8 | if nums[j] in rule[v]: 9 | return j 10 | return -1 11 | 12 | def mySort(nums, rule, step=0): 13 | p=-1 14 | for i in range(len(nums)): 15 | p = findInvalid(nums, i, rule) 16 | if(p!=-1): 17 | nums = nums[:p]+[nums[i]]+nums[p:i]+nums[i+1:] 18 | break 19 | if(p==-1): 20 | return nums 21 | return mySort(nums, rule, step+1) 22 | 23 | 24 | 25 | 26 | def process(nums, rule): 27 | read = set() 28 | for n in nums: 29 | if n in rule and len(rule[n].intersection(read))>0: 30 | return 0 31 | read.add(n) 32 | return nums[len(nums)//2] 33 | 34 | 35 | rule = {} 36 | for l in sys.stdin: 37 | if len(l.strip())==0: 38 | break 39 | a,b = [int(x) for x in l.strip().split("|")] 40 | if a not in rule: 41 | rule[a]=set() 42 | rule[a].add(b) 43 | 44 | print(rule) 45 | 46 | sum = 0 47 | for l in sys.stdin: 48 | nums= [int(x) for x in l.strip().split(",")] 49 | points = process(nums, rule) 50 | if points != 0: 51 | #already valid 52 | continue 53 | nums = mySort(nums, rule) 54 | sum+=process(nums, rule) 55 | print(sum) 56 | -------------------------------------------------------------------------------- /2024/06/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | map = [l.strip() for l in sys.stdin] 4 | 5 | options = {"^":(">", (-1,0)), ">":("v", (0,1)), "v":("<", (1,0)), "<":("^", (0,-1))} 6 | 7 | 8 | pos=(0,0) 9 | dir = ">" 10 | for i in range(len(map)): 11 | for j in range(len(map[i])): 12 | if map[i][j] in options: 13 | pos=(i,j) 14 | dir=map[i][j] 15 | break 16 | while (pos[0]>=0 and pos[0]=0 and pos[1]=len(map) or nj<0 or nj>=len(map[ni]): 25 | pos=(ni,nj) 26 | continue 27 | if map[ni][nj]=="#": 28 | dir=nextDir 29 | continue 30 | pos=(ni, nj) 31 | 32 | step = 0 33 | for i in map: 34 | for j in i: 35 | if j=="X": 36 | step+=1 37 | print(step) 38 | -------------------------------------------------------------------------------- /2024/06/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def test(map, pos, dir,options, ob): 4 | # print("testing", ob) 5 | visit=set() 6 | 7 | while (pos[0]>=0 and pos[0]=0 and pos[1]=len(map) or nj<0 or nj>=len(map[ni]): 17 | pos=(ni,nj) 18 | continue 19 | if map[ni][nj]=="#" or (ni,nj)==ob: 20 | #print((ni,nj)==ob, ob) 21 | dir=nextDir 22 | continue 23 | pos=(ni, nj) 24 | return False 25 | 26 | 27 | map = [l.strip() for l in sys.stdin] 28 | 29 | options = {"^":(">", (-1,0)), ">":("v", (0,1)), "v":("<", (1,0)), "<":("^", (0,-1))} 30 | 31 | 32 | pos=(0,0) 33 | dir = ">" 34 | for i in range(len(map)): 35 | for j in range(len(map[i])): 36 | if map[i][j] in options: 37 | pos=(i,j) 38 | dir=map[i][j] 39 | break 40 | 41 | initpos= pos 42 | initdir = dir 43 | while (pos[0]>=0 and pos[0]=0 and pos[1]=len(map) or nj<0 or nj>=len(map[ni]): 52 | pos=(ni,nj) 53 | continue 54 | if map[ni][nj]=="#": 55 | dir=nextDir 56 | continue 57 | pos=(ni, nj) 58 | 59 | ob = [] 60 | for i in range(len(map)): 61 | for j in range(len(map[i])): 62 | if map[i][j]=="X": 63 | ob.append((i,j)) 64 | print(len(ob)) 65 | 66 | count=0 67 | for x in ob: 68 | if test(map, initpos,initdir,options, x): 69 | #print(x) 70 | count+=1 71 | print(count) 72 | -------------------------------------------------------------------------------- /2024/07/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def test(k,v): 4 | if v[0]>k: 5 | return False 6 | if len(v)==1: 7 | return v[0]==k 8 | if(test(k, [v[0]+v[1]]+v[2:])): 9 | return True 10 | if(test(k, [v[0]*v[1]]+v[2:])): 11 | return True 12 | return False 13 | 14 | 15 | sum=0 16 | 17 | for l in sys.stdin: 18 | expected,rest=l.rstrip().split(":") 19 | v=[int(x.strip()) for x in rest.strip().split()] 20 | k=int(expected) 21 | if(test(k,v)): 22 | sum+=k 23 | print(sum) 24 | -------------------------------------------------------------------------------- /2024/07/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def test(k,v): 4 | if v[0]>k: 5 | return False 6 | if len(v)==1: 7 | return v[0]==k 8 | if(test(k, [v[0]+v[1]]+v[2:])): 9 | return True 10 | if(test(k, [v[0]*v[1]]+v[2:])): 11 | return True 12 | if(test(k, [int(str(v[0])+str(v[1]))]+v[2:])): 13 | return True 14 | return False 15 | 16 | 17 | sum=0 18 | 19 | for l in sys.stdin: 20 | expected,rest=l.rstrip().split(":") 21 | v=[int(x.strip()) for x in rest.strip().split()] 22 | k=int(expected) 23 | if(test(k,v)): 24 | sum+=k 25 | print(sum) 26 | -------------------------------------------------------------------------------- /2024/08/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def valid(x, mat): 5 | return x[0]>=0 and x[0]=0 and x[1]=0 and x[0]=0 and x[1]i: 23 | for _ in range(v): 24 | while last>i and a[last]==0: 25 | last-=2 26 | if last<=i: 27 | break 28 | sum+=((last//2)*block) 29 | #print((last//2), end='') 30 | block+=1 31 | a[last]-=1 32 | #print('') 33 | print(sum) 34 | -------------------------------------------------------------------------------- /2024/09/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def find(v,i, a): 4 | print("find", v,i) 5 | for j in range(1,i,2): 6 | if a[j]>=v: 7 | print("return if", j, a[j]) 8 | return j 9 | print("return f", i) 10 | return i 11 | 12 | #print(fat) 13 | 14 | a = [l.strip() for l in sys.stdin][0] 15 | disk = [] 16 | 17 | for i in range(len(a)): 18 | x = int(a[i]) 19 | if i%2==0: 20 | disk.append((i//2, x)) 21 | else: 22 | disk.append((-1, x)) 23 | #print(disk) 24 | i = len(disk)-1 25 | while i>0: 26 | v,s = disk[i] 27 | if v==-1: 28 | #empty space 29 | i-=1 30 | continue 31 | ni = -1 32 | for j in range(i): 33 | nv,ns = disk[j] 34 | if nv==-1 and ns>=s: 35 | ni = j 36 | break 37 | if ni==-1: 38 | i-=1 39 | continue 40 | _,ss = disk[ni] 41 | disk = disk[:ni]+[(v,s), (-1, ss-s)]+disk[ni+1:i]+[(-1,s)]+disk[i+1:] 42 | #print(disk) 43 | sum = 0 44 | block = 0 45 | for i in disk: 46 | v,s = i 47 | if v ==-1: 48 | block+=s 49 | continue 50 | for j in range(s): 51 | sum+= block*v 52 | block+=1 53 | print(sum) 54 | -------------------------------------------------------------------------------- /2024/10/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | alternatives={ 4 | (-1,0), 5 | (0,1), 6 | (1,0), 7 | (0,-1) 8 | } 9 | 10 | def dfs(mat, i,j,t, prev=-1): 11 | #print("dfs", i,j,prev) 12 | if i<0 or i>=len(mat) or j<0 or j>=len(mat[i]): 13 | return set() 14 | v = mat[i][j] 15 | if v!= prev+1: 16 | return set() 17 | if v == t: 18 | return {(i,j)} 19 | r = set() 20 | for a in alternatives: 21 | r=r.union(dfs(mat,i+a[0], j+a[1], t,v)) 22 | return r 23 | 24 | mat = [[int(x) for x in l.strip()] for l in sys.stdin] 25 | #print(mat) 26 | s = 0 27 | for i in range(len(mat)): 28 | for j in range(len(mat[i])): 29 | if mat[i][j]==0: 30 | #print("call ",i,j) 31 | r=dfs(mat, i,j,9) 32 | #print("r",r) 33 | s+=len(r) 34 | print(s) 35 | -------------------------------------------------------------------------------- /2024/10/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | alternatives={ 4 | (-1,0), 5 | (0,1), 6 | (1,0), 7 | (0,-1) 8 | } 9 | 10 | def dfs(mat, i,j,t, prev=-1): 11 | #print("dfs", i,j,prev) 12 | if i<0 or i>=len(mat) or j<0 or j>=len(mat[i]): 13 | return 0 14 | v = mat[i][j] 15 | if v!= prev+1: 16 | return 0 17 | if v == t: 18 | return 1 19 | r = 0 20 | for a in alternatives: 21 | r+=dfs(mat,i+a[0], j+a[1], t,v) 22 | return r 23 | 24 | mat = [[int(x) for x in l.strip()] for l in sys.stdin] 25 | #print(mat) 26 | s = 0 27 | for i in range(len(mat)): 28 | for j in range(len(mat[i])): 29 | if mat[i][j]==0: 30 | #print("call ",i,j) 31 | r=dfs(mat, i,j,9) 32 | #print("r",r) 33 | s+=r 34 | print(s) 35 | -------------------------------------------------------------------------------- /2024/11/p1.exs: -------------------------------------------------------------------------------- 1 | defmodule P11 do 2 | def calc(_, 0) do 3 | 1 4 | end 5 | 6 | def calc(0, limit) do 7 | calc(1, limit - 1) 8 | end 9 | 10 | def calc(x, limit) do 11 | case :ets.lookup(:mem, [x, limit]) do 12 | [{_, v} | _] -> 13 | # IO.inspect("hit #{x} #{limit} -> #{v}") 14 | v 15 | 16 | [] -> 17 | result = do_calc(x, limit) 18 | # IO.inspect("miss #{x} #{limit} -> #{result}") 19 | :ets.insert(:mem, {[x, limit], result}) 20 | result 21 | end 22 | end 23 | 24 | def do_calc(x, limit) do 25 | size = round(:math.floor(:math.log10(x)) + 1) 26 | 27 | if rem(size, 2) == 0 do 28 | mid = div(size, 2) 29 | calc(div(x, 10 ** mid), limit - 1) + calc(rem(x, 10 ** mid), limit - 1) 30 | else 31 | calc(x * 2024, limit - 1) 32 | end 33 | end 34 | end 35 | 36 | limit = 25 37 | :ets.new(:mem, [:named_table, :public]) 38 | 39 | IO.read(:stdio, :eof) 40 | |> String.split("\n", trim: true) 41 | |> IO.inspect() 42 | |> Enum.flat_map(fn x -> String.split(x, " ", trim: true) end) 43 | |> Enum.map(&String.to_integer/1) 44 | |> IO.inspect() 45 | |> Enum.map(fn x -> P11.calc(x, limit) end) 46 | |> IO.inspect() 47 | |> Enum.sum() 48 | |> IO.inspect() 49 | -------------------------------------------------------------------------------- /2024/11/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | l = [[int(x) for x in l.strip().split()] for l in sys.stdin][0] 3 | 4 | 5 | def simulate(l): 6 | result = [] 7 | for x in l: 8 | if x == 0: 9 | result.append(1) 10 | continue 11 | s = str(x) 12 | if len(s)%2==0: 13 | result.append(int(s[:len(s)//2])) 14 | result.append(int(s[len(s)//2:])) 15 | continue 16 | result.append(x*2024) 17 | return result 18 | 19 | #print(l) 20 | for i in range(25): 21 | l = simulate(l) 22 | #print(len(l)) 23 | print(len(l)) 24 | -------------------------------------------------------------------------------- /2024/11/p2.exs: -------------------------------------------------------------------------------- 1 | defmodule P11 do 2 | def calc(_, 0) do 3 | 1 4 | end 5 | 6 | def calc(0, limit) do 7 | calc(1, limit - 1) 8 | end 9 | 10 | def calc(x, limit) do 11 | case :ets.lookup(:mem, [x, limit]) do 12 | [{_, v} | _] -> 13 | # IO.inspect("hit #{x} #{limit} -> #{v}") 14 | v 15 | 16 | [] -> 17 | result = do_calc(x, limit) 18 | # IO.inspect("miss #{x} #{limit} -> #{result}") 19 | :ets.insert(:mem, {[x, limit], result}) 20 | result 21 | end 22 | end 23 | 24 | def do_calc(x, limit) do 25 | size = round(:math.floor(:math.log10(x)) + 1) 26 | 27 | if rem(size, 2) == 0 do 28 | mid = div(size, 2) 29 | calc(div(x, 10 ** mid), limit - 1) + calc(rem(x, 10 ** mid), limit - 1) 30 | else 31 | calc(x * 2024, limit - 1) 32 | end 33 | end 34 | end 35 | 36 | limit = 75 37 | :ets.new(:mem, [:named_table, :public]) 38 | 39 | IO.read(:stdio, :eof) 40 | |> String.split("\n", trim: true) 41 | |> IO.inspect() 42 | |> Enum.flat_map(fn x -> String.split(x, " ", trim: true) end) 43 | |> Enum.map(&String.to_integer/1) 44 | |> IO.inspect() 45 | |> Enum.map(fn x -> P11.calc(x, limit) end) 46 | |> IO.inspect() 47 | |> Enum.sum() 48 | |> IO.inspect() 49 | -------------------------------------------------------------------------------- /2024/11/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | 4 | l = [[int(x) for x in l.strip().split()] for l in sys.stdin][0] 5 | 6 | def calc(mem, x, l): 7 | if l == 0: 8 | return 1 9 | if x in mem[l]: 10 | return mem[l][x] 11 | if x == 0: 12 | mem[l][x]=calc(mem,1,l-1) 13 | elif (int(math.log10(x))+1)%2==0: 14 | s = str(x) 15 | mem[l][x] = calc(mem, int(s[:len(s)//2]), l-1) + calc(mem, int(s[len(s)//2:]), l-1) 16 | else: 17 | mem[l][x]=calc(mem, x*2024, l-1) 18 | return mem[l][x] 19 | 20 | limit = 76 21 | 22 | mem = [{} for i in range(limit)] 23 | 24 | for i in range(limit): 25 | print(sum([calc(mem,x,i) for x in l])) 26 | -------------------------------------------------------------------------------- /2024/12/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | alternatives = [ 5 | (-1,0), 6 | (0,-1), 7 | (1,0), 8 | (0,1) 9 | ] 10 | 11 | def invalid(x,y,mat): 12 | return not (x>=0 and x=0 and y":((1,0), (-1,0)), "v":((0,1), (0,-1)), "<":((-1,0), (1,0))} 11 | sym = { 12 | (-1,0): '^', 13 | (0,-1): '<', 14 | (1,0): 'v', 15 | (0,1): '>' 16 | 17 | 18 | } 19 | 20 | def invalid(x,y,mat): 21 | return not (x>=0 and x=0 and yv< 27 | x = e[k] 28 | a,b = direction[k] 29 | while len(x)>0: 30 | p = x.pop() 31 | #walk into a removing 32 | k = (p[0]+a[0], p[1]+a[1]) 33 | while k in x: 34 | x.remove(k) 35 | k = (k[0]+a[0], k[1]+a[1]) 36 | 37 | #walk into b removing 38 | k = (p[0]+b[0], p[1]+b[1]) 39 | while k in x: 40 | x.remove(k) 41 | k = (k[0]+b[0], k[1]+b[1]) 42 | s+=1 43 | return s 44 | 45 | 46 | def flood(mat, start, visit): 47 | v = mat[start[0]][start[1]] 48 | a = 0 49 | p = 0 50 | e = {} 51 | for k in sym.values(): 52 | e[k]=set() 53 | q = deque([start]) 54 | while q: 55 | d = q.popleft() 56 | if d in visit: 57 | continue 58 | visit.add(d) 59 | a+=1 60 | for u in alternatives: 61 | x = d[0]+u[0] 62 | y = d[1]+u[1] 63 | if invalid(x,y,mat): 64 | p+=1 65 | e[sym[u]].add(d) 66 | elif mat[x][y]!=v: 67 | p+=1 68 | e[sym[u]].add(d) 69 | else: 70 | q.append((x,y)) 71 | return a,p,e 72 | 73 | mat = [l.strip() for l in sys.stdin] 74 | 75 | visited = set() 76 | 77 | resp = 0 78 | for i in range(len(mat)): 79 | for j in range(len(mat[i])): 80 | if (i,j) in visited: 81 | continue 82 | a,p,e = flood(mat, (i, j), visited) 83 | print("region of ", mat[i][j], " area ",a, " perimeter ",p) 84 | #print("external ",e) 85 | # i,j is a top-left corner 86 | s = walkBorder(e) 87 | print("slices ", s) 88 | resp += a*s 89 | print(resp) 90 | -------------------------------------------------------------------------------- /2024/13/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def parseLine(line, div='+'): 4 | x,y = line.split(':')[1].strip().split(",") 5 | x = int(x.split(div)[1].strip()) 6 | y = int(y.split(div)[1].strip()) 7 | return x,y 8 | def solve(la, lb, lp): 9 | xa,ya = parseLine(la) 10 | xb,yb = parseLine(lb) 11 | xp,yp = parseLine(lp, "=") 12 | 13 | # I: xa*A + xb*B = xp 14 | # II: ya*A + yb*B = yp II 15 | 16 | # III (from I): A = (xp - xb*B)/xa 17 | # IV (apply III on II): ya*[(xp - xb*B)/xa] + yb*B = yp 18 | # => ya*(xp-xb*B) + xa*yb*B = yp*xa 19 | # => B*(xa*yb -ya*xb) = yp*xa - ya*xp 20 | # => B = (yp*xa - ya*xp)/(xa*yb -ya*xb) 21 | # invalid if B is not int 22 | # apply IV on III 23 | # invalid if A is not int 24 | 25 | b = (yp*xa - ya*xp)/(xa*yb -ya*xb) 26 | a = (xp - xb*b)/xa 27 | if int(b)!=b or int(a)!=a: 28 | return 0 29 | if a>100 or a<0 or b>100 or b<0: 30 | return 0 31 | return a*3 + b 32 | 33 | tokens = 0 34 | prob = [] 35 | for l in sys.stdin: 36 | if len(l.strip()) == 0: 37 | tokens+=solve(*prob) 38 | prob = [] 39 | continue 40 | prob.append(l.strip()) 41 | tokens+=solve(*prob) 42 | print(tokens) 43 | -------------------------------------------------------------------------------- /2024/13/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def parseLine(line, div='+'): 4 | x,y = line.split(':')[1].strip().split(",") 5 | x = int(x.split(div)[1].strip()) 6 | y = int(y.split(div)[1].strip()) 7 | return x,y 8 | def solve(la, lb, lp): 9 | xa,ya = parseLine(la) 10 | xb,yb = parseLine(lb) 11 | xp,yp = parseLine(lp, "=") 12 | xp+=10000000000000 13 | yp+=10000000000000 14 | 15 | # I: xa*A + xb*B = xp 16 | # II: ya*A + yb*B = yp II 17 | 18 | # III (from I): A = (xp - xb*B)/xa 19 | # IV (apply III on II): ya*[(xp - xb*B)/xa] + yb*B = yp 20 | # => ya*(xp-xb*B) + xa*yb*B = yp*xa 21 | # => B*(xa*yb -ya*xb) = yp*xa - ya*xp 22 | # => B = (yp*xa - ya*xp)/(xa*yb -ya*xb) 23 | # invalid if B is not int 24 | # apply IV on III 25 | # invalid if A is not int 26 | 27 | b = (yp*xa - ya*xp)/(xa*yb -ya*xb) 28 | a = (xp - xb*b)/xa 29 | if int(b)-b or int(a)!=a: 30 | return 0 31 | if a<0 or b<0: 32 | return 0 33 | return a*3 + b 34 | 35 | tokens = 0 36 | prob = [] 37 | for l in sys.stdin: 38 | if len(l.strip()) == 0: 39 | tokens+=solve(*prob) 40 | prob = [] 41 | continue 42 | prob.append(l.strip()) 43 | tokens+=solve(*prob) 44 | print(tokens) 45 | -------------------------------------------------------------------------------- /2024/14/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def parse(x): 4 | p,v = x.strip().split() 5 | px,py = p.split("=")[1].split(",") 6 | vx,vy = v.split("=")[1].split(",") 7 | return ((int(px),int(py)), (int(vx), int(vy))) 8 | 9 | r = [parse(l) for l in sys.stdin] 10 | 11 | rounds = 100 12 | size=(101,103) 13 | mx = size[0]//2 14 | my = size[1]//2 15 | 16 | tl = 0 17 | tr = 0 18 | bl = 0 19 | br = 0 20 | for p,v in r: 21 | nx = (p[0] +v[0]*rounds)%size[0] 22 | ny = (p[1] +v[1]*rounds)%size[1] 23 | if nxmy: 26 | tr+=1 27 | if nx>mx and nymx and ny>my: 30 | br+=1 31 | print(tl,tr,bl,br) 32 | print(tl*tr*bl*br) 33 | -------------------------------------------------------------------------------- /2024/14/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | 4 | def parse(x): 5 | p,v = x.strip().split() 6 | px,py = p.split("=")[1].split(",") 7 | vx,vy = v.split("=")[1].split(",") 8 | return ((int(px),int(py)), (int(vx), int(vy))) 9 | 10 | r = [parse(l) for l in sys.stdin] 11 | 12 | size=(101,103) 13 | mx = size[0]//2 14 | my = size[1]//2 15 | 16 | sfmin=math.inf 17 | sfmax=0 18 | resp = 0 19 | for i in range(size[0]*size[1]): 20 | tl = 0 21 | tr = 0 22 | bl = 0 23 | br = 0 24 | for p,v in r: 25 | nx = (p[0] +v[0]*i)%size[0] 26 | ny = (p[1] +v[1]*i)%size[1] 27 | if nxmy: 30 | tr+=1 31 | if nx>mx and nymx and ny>my: 34 | br+=1 35 | sf = tl*tr*bl*br 36 | #print(i,sf) 37 | sfmax=max(sfmax,sf) 38 | if sf":(0,1), 7 | "v":(1,0) 8 | } 9 | 10 | def printa(c,mat): 11 | if 1>0: 12 | return 13 | print(c) 14 | for l in mat: 15 | print("".join(l)) 16 | 17 | def apply(mat,p, c): 18 | move=False 19 | delta = d[c] 20 | nx = p[0]+delta[0] 21 | ny = p[1]+delta[1] 22 | 23 | bx = nx 24 | by = ny 25 | box = False 26 | 27 | while mat[bx][by] == 'O': 28 | box=True 29 | bx = bx+delta[0] 30 | by = by+delta[1] 31 | if box and mat[bx][by]=='.': 32 | mat[bx][by]='O' 33 | move = True 34 | if mat[nx][ny]=='.': 35 | move=True 36 | 37 | if move: 38 | mat[p[0]][p[1]] = '.' 39 | mat[nx][ny]='@' 40 | return (nx,ny) 41 | return p 42 | 43 | mat = [] 44 | 45 | for l in sys.stdin: 46 | if len(l.strip())==0: 47 | break 48 | mat.append(list(l.strip())) 49 | 50 | printa(0,mat) 51 | commands = "".join([l.strip() for l in sys.stdin]) 52 | #print(commands) 53 | 54 | s = (0,0) 55 | for i in range(len(mat)): 56 | for j in range(len(mat[i])): 57 | if mat[i][j]=='@': 58 | s = (i,j) 59 | for c in commands: 60 | s=apply(mat,s,c) 61 | printa(c,mat) 62 | result = 0 63 | for i in range(len(mat)): 64 | for j in range(len(mat[i])): 65 | if mat[i][j]=='O': 66 | result+= 100*i+j 67 | print(result) 68 | -------------------------------------------------------------------------------- /2024/15/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | d={ 4 | "<":(0,-1), 5 | "^":(-1,0), 6 | ">":(0,1), 7 | "v":(1,0) 8 | } 9 | 10 | def printa(c,mat): 11 | if 1>0: 12 | return 13 | print(c) 14 | for l in mat: 15 | print("".join(l)) 16 | print() 17 | 18 | def check(mat, delta, opts): 19 | nopts = set() 20 | for ox,oy in opts: 21 | v = mat[ox+delta][oy] 22 | if v == '.': 23 | continue 24 | if v =='#': 25 | return 0 26 | nopts.add((ox+delta,oy)) 27 | nopts.add((ox+delta,oy + (1 if v=='[' else -1))) 28 | if len(nopts) == 0: 29 | return 1 30 | r = check(mat, delta, nopts) 31 | if r == 0: 32 | return 0 33 | return r+1 34 | 35 | def edit(mat, delta, opts, fit): 36 | if fit<0: 37 | return 38 | nopts = set() 39 | maybeDelete = set() 40 | for ox,oy,nv in opts: 41 | v = mat[ox+delta][oy] 42 | if v in '[]': 43 | nopts.add((ox+delta, oy, v)) 44 | ny = oy +(1 if v=='[' else -1) 45 | nopts.add((ox+delta, ny, '['if v==']'else']')) 46 | maybeDelete.add((ox, ny)) 47 | mat[ox+delta][oy]=nv 48 | for x,y,_ in opts: 49 | maybeDelete.discard((x,y)) 50 | for x, y in maybeDelete: 51 | mat[x+delta][y]='.' 52 | edit(mat, delta, nopts, fit-1) 53 | 54 | def moveh(mat,p,c): 55 | delta = d[c] 56 | nx = p[0]+delta[0] 57 | ny = p[1]+delta[1] 58 | 59 | bx,by = nx,ny 60 | while mat[bx][by] in "[]": 61 | bx = bx+delta[0] 62 | by = by+delta[1] 63 | if mat[bx][by]=='#': 64 | return p 65 | 66 | mat[p[0]][p[1]]='.' 67 | mat[nx][ny] = '@' 68 | box ="[]" 69 | b=0 if c=='>' else 1 70 | for i in range(abs(ny-by)): 71 | mat[bx][ny+((i+1)*delta[1])]=box[(b+i)%2] 72 | i+=1 73 | return (nx,ny) 74 | 75 | def movev(mat,p,c): 76 | delta = d[c] 77 | nx = p[0]+delta[0] 78 | ny = p[1]+delta[1] 79 | 80 | v = mat[nx][ny] 81 | 82 | if v=='.': 83 | mat[p[0]][p[1]]='.' 84 | mat[nx][ny] = '@' 85 | return (nx,ny) 86 | if v=='#': 87 | return p 88 | 89 | #found box, check if fit 90 | fit = check(mat, delta[0], [(nx,ny), (nx,ny + (1 if v=='[' else -1))]) 91 | 92 | if fit == 0 : 93 | return p 94 | 95 | #fit has the n# of rows will be edited 96 | mat[p[0]][p[1]]='.' 97 | edit(mat, delta[0], [(*p, '@')], fit) 98 | return (nx,ny) 99 | 100 | def apply(mat,p, c): 101 | if c in "<>": 102 | return moveh(mat, p,c) 103 | else: 104 | return movev(mat,p,c) 105 | 106 | mat = [] 107 | 108 | for l in sys.stdin: 109 | if len(l.strip())==0: 110 | break 111 | l = list(l.strip()) 112 | x=[] 113 | for c in l: 114 | if c=='@': 115 | x.append('@') 116 | x.append('.') 117 | elif c=='O': 118 | x.append('[') 119 | x.append(']') 120 | else: 121 | x.append(c) 122 | x.append(c) 123 | mat.append(x) 124 | 125 | printa(0,mat) 126 | commands = "".join([l.strip() for l in sys.stdin]) 127 | #print(commands) 128 | 129 | s = (0,0) 130 | for i in range(len(mat)): 131 | for j in range(len(mat[i])): 132 | if mat[i][j]=='@': 133 | s = (i,j) 134 | for c in commands: 135 | s=apply(mat,s,c) 136 | printa(c,mat) 137 | result = 0 138 | for i in range(len(mat)): 139 | for j in range(len(mat[i])): 140 | if mat[i][j]=='[': 141 | result+= 100*i+j 142 | print(result) 143 | -------------------------------------------------------------------------------- /2024/16/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | import math 4 | 5 | mat = [l.strip() for l in sys.stdin] 6 | options = { 7 | "^":([">", "<"], (-1,0)), 8 | ">":(["v", "^"], (0,1)), 9 | "v":(["<", ">"], (1,0)), 10 | "<":(["^", "v"], (0,-1)) 11 | } 12 | 13 | def dfs(mat, start, end): 14 | values = [] 15 | for i in range(len(mat)): 16 | values.append([]) 17 | for j in range(len(mat[i])): 18 | values[i].append( 19 | { 20 | ">":math.inf, 21 | "v":math.inf, 22 | "<":math.inf, 23 | "^":math.inf 24 | } 25 | ) 26 | q = deque([(*start, ">", 0)]) 27 | while q: 28 | i,j,d,p = q.popleft() 29 | if len(q)%100==0: 30 | print(len(q)) 31 | if i<0 or i>=len(mat) or j<0 or j>=len(mat[i]): 32 | continue 33 | if mat[i][j]=='#': 34 | continue 35 | if values[i][j][d]", "<"], (-1,0)), 8 | ">":(["v", "^"], (0,1)), 9 | "v":(["<", ">"], (1,0)), 10 | "<":(["^", "v"], (0,-1)) 11 | } 12 | 13 | def dfs(mat, start, end): 14 | values = [] 15 | for i in range(len(mat)): 16 | values.append([]) 17 | for j in range(len(mat[i])): 18 | values[i].append( 19 | { 20 | ">":(math.inf, set()), 21 | "v":(math.inf, set()), 22 | "<":(math.inf, set()), 23 | "^":(math.inf, set()) 24 | } 25 | ) 26 | q = deque([(*start, ">", 0, set([start]))]) 27 | while q: 28 | i,j,d,p, path = q.popleft() 29 | if len(q)%100==0: 30 | print(len(q)) 31 | if i<0 or i>=len(mat) or j<0 or j>=len(mat[i]): 32 | continue 33 | if mat[i][j]=='#': 34 | continue 35 | path.add((i,j)) 36 | currentMin, currentPath = values[i][j][d] 37 | if currentMin=0 and pc=0 and pc=0 and c[0]=0 and c[1]0: 69 | _,i,j = heapq.heappop(olist) 70 | closed[i][j]=True 71 | for d in directions: 72 | ni = i+d[0] 73 | nj = j+d[1] 74 | 75 | if not valid((ni,nj)) or (ni,nj) in points or closed[ni][nj]: 76 | continue 77 | g = details[i][j][3] +1 78 | if (ni,nj)==dst: 79 | details[ni][nj]=(i,j,g,g,0) 80 | return True,g 81 | else: 82 | h = calc(i,j,*dst) 83 | f = g+h 84 | cf=details[ni][nj][2] 85 | if cf==math.inf or cf>f: 86 | heapq.heappush(olist, (f, ni,nj)) 87 | details[ni][nj]=(i,j,f,g,h) 88 | return False,0 89 | 90 | 91 | points = [] 92 | for l in sys.stdin: 93 | x,y = l.strip().split(",") 94 | points.append((int(y), int(x))) 95 | points = points[:limit] 96 | #print(points) 97 | #printa(points) 98 | #print(bfs((0,0), (size-1,size-1), points)) 99 | print(astar((0,0), (size-1, size-1), points)) 100 | #2390 to high 101 | -------------------------------------------------------------------------------- /2024/18/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | import heapq 4 | from collections import deque 5 | size = 71 6 | limit = 1024 7 | directions = [ 8 | (0,1),(-1,0), (0,-1), (1,0) 9 | ] 10 | 11 | def valid(c): 12 | return c[0]>=0 and c[0]=0 and c[1]0: 79 | _,i,j = heapq.heappop(olist) 80 | closed[i][j]=True 81 | for d in directions: 82 | ni = i+d[0] 83 | nj = j+d[1] 84 | 85 | if not valid((ni,nj)) or (ni,nj) in points or closed[ni][nj]: 86 | continue 87 | g = details[i][j][3] +1 88 | if (ni,nj)==dst: 89 | details[ni][nj]=(i,j,g,g,0) 90 | return True,g, path(details, dst) 91 | else: 92 | h = calc(i,j,*dst) 93 | f = g+h 94 | cf=details[ni][nj][2] 95 | if cf==math.inf or cf>f: 96 | heapq.heappush(olist, (f, ni,nj)) 97 | details[ni][nj]=(i,j,f,g,h) 98 | return False,0,[] 99 | 100 | 101 | points = [] 102 | for l in sys.stdin: 103 | x,y = l.strip().split(",") 104 | points.append((int(y), int(x))) 105 | 106 | #print(points) 107 | #printa(points) 108 | #print(bfs((0,0), (size-1,size-1), points)) 109 | p = [] 110 | f = False 111 | g = 0 112 | for i in range(limit, len(points)): 113 | c = points[:i+1] 114 | if points[i] in p or len(p)==0: 115 | f,g,p=astar((0,0), (size-1, size-1), c) 116 | if not f: 117 | print(points[i][1],",",points[i][0]) 118 | break 119 | #print(i,"/",len(points)," ",g) 120 | 121 | -------------------------------------------------------------------------------- /2024/19/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | 5 | def test(design, cache={}): 6 | if design in cache: 7 | return cache[design] 8 | 9 | if len(design)==0: 10 | cache[design]=True 11 | return True 12 | for o in options: 13 | if design.startswith(o) and test(design[len(o):], cache): 14 | cache[design]=True 15 | return True 16 | cache[design]=False 17 | return False 18 | 19 | 20 | options = [l.strip() for l in input().strip().split(",")] 21 | input() 22 | 23 | query = [l.strip() for l in sys.stdin] 24 | 25 | result = 0 26 | for q in query: 27 | if test(q): 28 | result+=1 29 | print(result) 30 | -------------------------------------------------------------------------------- /2024/19/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def test(design, cache={}): 4 | if design in cache: 5 | return cache[design] 6 | 7 | if len(design)==0: 8 | cache[design]=1 9 | return 1 10 | count = 0 11 | for o in options: 12 | if design.startswith(o): 13 | count+= test(design[len(o):], cache) 14 | cache[design]=count 15 | return count 16 | 17 | 18 | options = [l.strip() for l in input().strip().split(",")] 19 | input() 20 | 21 | query = [l.strip() for l in sys.stdin] 22 | 23 | result = 0 24 | for q in query: 25 | result+= test(q) 26 | print(result) 27 | -------------------------------------------------------------------------------- /2024/20/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | import heapq 4 | from collections import deque 5 | directions = [ 6 | (0,1),(-1,0), (0,-1), (1,0) 7 | ] 8 | 9 | def valid(x,y,mat): 10 | return x>=0 and x=0 and y=100: 52 | #print(k,p, nv, v) 53 | #print(v-nv-2) 54 | count+=1 55 | print(count) 56 | 57 | -------------------------------------------------------------------------------- /2024/20/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | import heapq 4 | from collections import deque 5 | directions = [ 6 | (0,1),(-1,0), (0,-1), (1,0) 7 | ] 8 | 9 | def valid(x,y,mat): 10 | return x>=0 and x=0 and y=100: 52 | #print(k,k2, v,v2, count) 53 | count+=1 54 | print(count) 55 | 56 | -------------------------------------------------------------------------------- /2024/21/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | import math 4 | 5 | direction = { 6 | (0,1):'>', 7 | (-1,0):'^', 8 | (0,-1):'<', 9 | (1,0):"v" 10 | } 11 | 12 | 13 | def valid(mat, x,y): 14 | return x>=0 and x=0 and y" 77 | ] 78 | dpad2cord = toCord(dpad) 79 | dpadpaths = precalc(dpad) #precalc 80 | 81 | 82 | def genericpad(c,p2cord, allpaths, mat, start = 'A'): 83 | current = p2cord[start] 84 | options = [] 85 | for i in c: 86 | target = p2cord[i] 87 | 88 | paths = allpaths[(*current, *target)] if current!=target else [['A']] 89 | #print("going from ", current, "(",mat[current[0]][current[1]],") to ", target, "(",mat[target[0]][target[1]],") path ", paths) 90 | response = [] 91 | if len(options) ==0: 92 | response = []+paths 93 | else: 94 | for o in options: 95 | for p in paths: 96 | response.append(o+p) 97 | options = response 98 | current = target 99 | m = min([len(o) for o in options]) 100 | return ["".join(o) for o in options if len(o)==m] 101 | def numpad(c): 102 | #print("numapd",c) 103 | return genericpad(c, pad2cord, padpaths, pad) 104 | def dirpad(c): 105 | r = [] 106 | for x in c: 107 | #print("dirpad", x) 108 | r.extend(genericpad(x, dpad2cord, dpadpaths, dpad)) 109 | m = min(len(x) for x in r ) 110 | return [x for x in r if len(x)==m] 111 | def solve(c): 112 | options = dirpad(dirpad(numpad(c))) 113 | #print(options) 114 | return min([len(x) for x in options]) 115 | 116 | 117 | 118 | l = [l.strip() for l in sys.stdin] 119 | 120 | resp = 0 121 | for c in l: 122 | numeric = int(c.replace('A', '')) 123 | size = solve(c) 124 | print(size, numeric) 125 | resp+= size*numeric 126 | print(resp) 127 | 128 | -------------------------------------------------------------------------------- /2024/21/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | from functools import cache 4 | import math 5 | 6 | direction = { 7 | (0,1):'>', 8 | (-1,0):'^', 9 | (0,-1):'<', 10 | (1,0):"v" 11 | } 12 | 13 | 14 | def valid(mat, x,y): 15 | return x>=0 and x=0 and y" 78 | ] 79 | dpad2cord = toCord(dpad) 80 | dpadpaths = precalc(dpad) #precalc 81 | 82 | 83 | def genericpad(c,p2cord, allpaths, mat, start = 'A'): 84 | current = p2cord[start] 85 | options = [] 86 | for i in c: 87 | target = p2cord[i] 88 | 89 | paths = allpaths[(*current, *target)] if current!=target else [['A']] 90 | #print("going from ", current, "(",mat[current[0]][current[1]],") to ", target, "(",mat[target[0]][target[1]],") path ", paths) 91 | response = [] 92 | if len(options) ==0: 93 | response = []+paths 94 | else: 95 | for o in options: 96 | for p in paths: 97 | response.append(o+p) 98 | options = response 99 | current = target 100 | m = min([len(o) for o in options]) 101 | return ["".join(o) for o in options if len(o)==m] 102 | def numpad(c): 103 | #print("numapd",c) 104 | return genericpad(c, pad2cord, padpaths, pad) 105 | 106 | def dirpad(c, start): 107 | r = [] 108 | for x in c: 109 | #print("dirpad", x) 110 | r.extend(genericpad(x, dpad2cord, dpadpaths, dpad, start)) 111 | m = min(len(x) for x in r ) 112 | return [x for x in r if len(x)==m] 113 | @cache 114 | def dp(c,d): 115 | response = 0 116 | c = 'A'+c 117 | for i in range(1, len(c)): 118 | paths = genericpad(c[i], dpad2cord, dpadpaths, dpad, c[i-1]) 119 | if d ==0: 120 | response += min([len(path) for path in paths]) 121 | else: 122 | response += min(dp(path, d-1) for path in paths) 123 | return response 124 | 125 | def solve(c): 126 | #print(options) 127 | return min([dp(x,24) for x in numpad(c)]) 128 | 129 | 130 | 131 | l = [l.strip() for l in sys.stdin] 132 | 133 | resp = 0 134 | for c in l: 135 | numeric = int(c.replace('A', '')) 136 | size = solve(c) 137 | print(size, numeric) 138 | resp+= size*numeric 139 | print(resp) 140 | 141 | -------------------------------------------------------------------------------- /2024/22/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def calc(x, r): 4 | for i in range(r): 5 | x = (x^(x*64)) %16777216 6 | x = (x^(x//32))%16777216 7 | x = (x^(x*2048)) %16777216 8 | return x 9 | l =[int(l.strip()) for l in sys.stdin] 10 | 11 | r = 0 12 | for x in l: 13 | y = calc(x, 2000) 14 | print(x,y) 15 | r+=y 16 | print(r) 17 | -------------------------------------------------------------------------------- /2024/22/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def convert(l): # could be removed 4 | return "".join([chr(i+ord('m')) for i in l]) 5 | def calc(x, r): 6 | seq = [] 7 | diff=[] 8 | for i in range(r): 9 | a = x%10 10 | x = (x^(x*64)) %16777216 11 | x = (x^(x//32))%16777216 12 | x = (x^(x*2048)) %16777216 13 | diff.append((x%10)-a) 14 | seq.append(x%10) 15 | return x, seq,convert(diff) 16 | l =[int(l.strip()) for l in sys.stdin] 17 | 18 | dic={} 19 | for x in l: 20 | y,seq,diff = calc(x, 2000) 21 | seen = set() 22 | for i in range(len(diff)-3): 23 | pat = diff[i:i+4] 24 | point = seq[i+3] 25 | if pat not in seen: 26 | seen.add(pat) 27 | if pat not in dic: 28 | dic[pat]=0 29 | dic[pat]+=point 30 | #print(x,y) 31 | 32 | print(max([dic[x] for x in dic ])) 33 | -------------------------------------------------------------------------------- /2024/23/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def containsT(i,j,k): 4 | return i.startswith('t') or j.startswith('t') or k.startswith('t') 5 | edges={} 6 | 7 | for l in sys.stdin: 8 | a,b = l.strip().split("-") 9 | if a not in edges: 10 | edges[a]=set() 11 | edges[a].add(b) 12 | 13 | if b not in edges: 14 | edges[b]=set() 15 | edges[b].add(a) 16 | 17 | three = set() 18 | 19 | for i in edges: 20 | for j in edges[i]: 21 | for k in edges[j]: 22 | if k in edges[i] and containsT(i,j,k): 23 | three.add(tuple(sorted([i,j,k]))) 24 | print(len(three)) 25 | -------------------------------------------------------------------------------- /2024/23/p2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | def isComplete(x): 5 | r = x 6 | for i in x: 7 | r = r.intersection(edges[i]) 8 | return len(r)==len(x) 9 | 10 | def back(opt, x=set()): 11 | #print("back",x,opt) 12 | if len(opt) == 0: 13 | if isComplete(x): 14 | return x 15 | else: 16 | return set() 17 | local = opt.copy() 18 | hd = set([local.pop()]) 19 | 20 | consider = back(local,x.union(hd)) 21 | discard = back(local,x) 22 | if len(consider)>len(discard): 23 | return consider 24 | return discard 25 | 26 | edges={} 27 | 28 | for l in sys.stdin: 29 | a,b = l.strip().split("-") 30 | if a not in edges: 31 | edges[a]=set([a]) 32 | edges[a].add(b) 33 | 34 | if b not in edges: 35 | edges[b]=set([b]) 36 | edges[b].add(a) 37 | 38 | selected = set() 39 | for i in edges: 40 | current = back(edges[i]) 41 | if len(current)>len(selected): 42 | selected = current 43 | print(i) 44 | 45 | 46 | print(sorted(selected)) 47 | print(max([len(edges[i]) for i in edges])) 48 | -------------------------------------------------------------------------------- /2024/24/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def resolve(val, lazy, key): 4 | if key not in val and key not in lazy: 5 | return None 6 | if key in val: 7 | return val[key] 8 | a,op,b = lazy[key] 9 | a = resolve(val, lazy, a) 10 | b = resolve(val, lazy, b) 11 | if op == "AND": 12 | return a&b 13 | if op== "XOR": 14 | return a^b 15 | if op=="OR": 16 | return a|b 17 | raise Exception("error "+op) 18 | 19 | val={} 20 | 21 | l=input() 22 | while l!="": 23 | x,v= l.strip().split(": ") 24 | val[x]=int(v) 25 | l = input() 26 | 27 | lazy = {} 28 | for l in sys.stdin: 29 | x,v = l.strip().split(" -> ") 30 | lazy[v]=x.split() 31 | result="" 32 | z=0 33 | while True: 34 | r = resolve(val, lazy, f"z{z:02d}") 35 | if r==None: 36 | break 37 | result = str(r)+result 38 | z+=1 39 | print(result, int(result, 2)) 40 | 41 | -------------------------------------------------------------------------------- /2024/25/p1.py: -------------------------------------------------------------------------------- 1 | import sys 2 | def compat(a,b): 3 | if len(a)!=len(b): 4 | return False 5 | for i in range(len(a)): 6 | if a[i]+b[i]>7: 7 | return False 8 | return True 9 | def convert(mat): 10 | r = [0 for _ in range(len(mat[0]))] 11 | for i in range(len(mat)): 12 | for j in range(len(r)): 13 | if mat[i][j]=='#': 14 | r[j]+=1 15 | return r, mat[0].find('#')>=0 16 | tmp = [] 17 | k = [] 18 | l = [] 19 | for i in sys.stdin: 20 | if len(i.strip())==0: 21 | v,isl = convert(tmp) 22 | if isl: 23 | l.append(v) 24 | else: 25 | k.append(v) 26 | tmp.clear() 27 | else: 28 | tmp.append(i.strip()) 29 | v,isl = convert(tmp) 30 | if isl: 31 | l.append(v) 32 | else: 33 | k.append(v) 34 | 35 | resp = 0 36 | for i in k: 37 | for j in l: 38 | if compat(i,j): 39 | resp+=1 40 | print(resp) 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # adventOfCode 2 | 3 | [2021](https://adventofcode.com/2021) 4 | [2022](https://adventofcode.com/2022) 5 | 6 | # how to 7 | 8 | Python -> `cat {day}/input | python3 {day}/p1.py` 9 | 10 | JS -> `cat {day}/input | node {day}/p1.js` 11 | 12 | Pipes -> use a [pipes](https://pipes.intelie.com) console 👀 13 | --------------------------------------------------------------------------------