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 solution for 2019/12

+79
+73
2019/day12.py
··· 1 + import fileinput 2 + from copy import deepcopy 3 + from itertools import count 4 + 5 + from utils import parse_nums 6 + 7 + 8 + def gcd(a,b): 9 + """Compute the greatest common divisor of a and b""" 10 + while b > 0: 11 + a, b = b, a % b 12 + return a 13 + 14 + def lcm(a, b): 15 + """Compute the lowest common multiple of a and b""" 16 + return a * b / gcd(a, b) 17 + 18 + 19 + positions = [] 20 + for i, line in enumerate(fileinput.input()): 21 + line = line.strip() 22 + nums = parse_nums(line) 23 + positions.append(list(nums)) 24 + 25 + 26 + velocities = [[0] * 3 for _ in range(4)] 27 + 28 + INIT_POS = deepcopy(positions) 29 + INIT_VEL = deepcopy(velocities) 30 + CYCLES = [None, None, None] 31 + 32 + for i in count(start=1): 33 + # Update velocities 34 + for x in range(4): 35 + for y in range(x + 1, 4): 36 + for d in range(3): 37 + if positions[x][d] < positions[y][d]: 38 + velocities[x][d] += 1 39 + velocities[y][d] -= 1 40 + elif positions[x][d] > positions[y][d]: 41 + velocities[x][d] -= 1 42 + velocities[y][d] += 1 43 + 44 + # Update positions 45 + for x in range(4): 46 + for d in range(3): 47 + positions[x][d] += velocities[x][d] 48 + 49 + energy = 0 50 + 51 + for pos, vel in zip(positions, velocities): 52 + pot = sum(abs(p) for p in pos) 53 + kin = sum(abs(p) for p in vel) 54 + energy += pot * kin 55 + 56 + if i == 1000: 57 + print "Total energy after 1000 steps:", energy 58 + 59 + for d in range(3): 60 + if CYCLES[d] is not None: 61 + continue 62 + 63 + for m in range(4): 64 + if positions[m][d] != INIT_POS[m][d]: 65 + break 66 + if velocities[m][d] != INIT_VEL[m][d]: 67 + break 68 + else: 69 + CYCLES[d] = i 70 + 71 + if all(CYCLES): 72 + print "Steps for full cycle:", lcm(lcm(CYCLES[0], CYCLES[1]), CYCLES[2]) 73 + break
+4
2019/inputs/12.txt
··· 1 + <x=8, y=0, z=8> 2 + <x=0, y=-5, z=-10> 3 + <x=16, y=10, z=-5> 4 + <x=19, y=-10, z=-7>
+2
2019/outputs/12.txt
··· 1 + 12490 2 + 392733896255168