My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add 2022/13

+83
+83
2022/day13.py
··· 1 + import fileinput 2 + 3 + 4 + def right_order(a, b): 5 + for x, y in zip(a, b): 6 + if type(x) == int and type(y) == int: 7 + if int(x) < int(y): 8 + return True 9 + elif int(x) > int(y): 10 + return False 11 + else: 12 + continue 13 + elif type(x) == list and type(y) == list: 14 + # :( 15 + # if len(x) == 0: 16 + # return True 17 + # elif len(y) == 0: 18 + # return False 19 + ret = right_order(x, y) 20 + if ret is None: 21 + continue 22 + else: 23 + return ret 24 + else: 25 + if type(x) == int: 26 + ret = right_order([x], y) 27 + else: 28 + ret = right_order(x, [y]) 29 + 30 + if ret is None: 31 + continue 32 + return ret 33 + 34 + if len(a) < len(b): 35 + return True 36 + elif len(a) > len(b): 37 + return False 38 + 39 + return None 40 + 41 + 42 + # Solve part 1 while parsing input. 43 + packets = [] 44 + pair = [] 45 + part_1 = 0 46 + idx = 1 47 + for line in fileinput.input(): 48 + if not line.strip(): 49 + if right_order(*pair): 50 + part_1 += idx 51 + pair = [] 52 + idx += 1 53 + else: 54 + packet = eval(line.strip()) 55 + pair.append(packet) 56 + packets.append(packet) 57 + 58 + # Final pair because no trailing newline. 59 + if right_order(*pair): 60 + part_1 += idx 61 + 62 + print("Part 1:", part_1) 63 + 64 + 65 + # Solve Part 2. 66 + packets.insert(0, [[2]]) 67 + packets.insert(0, [[6]]) 68 + 69 + mapping = {} 70 + for i, p1 in enumerate(packets): 71 + count = 0 72 + for j, p2 in enumerate(packets): 73 + if i == j: 74 + continue 75 + 76 + if right_order(p2, p1): 77 + count += 1 78 + 79 + mapping[i] = count 80 + 81 + two = mapping[0] + 1 82 + six = mapping[1] + 1 83 + print("Part 2:", two*six)