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.

Update day12.py

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