You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.9 KiB
62 lines
1.9 KiB
import os
|
|
import re
|
|
from copy import deepcopy
|
|
from functools import reduce
|
|
from itertools import permutations
|
|
from math import gcd
|
|
|
|
inputfile = os.path.join(os.path.dirname(__file__), "input/day12_input")
|
|
|
|
|
|
def get_moons():
|
|
with open(inputfile) as fp:
|
|
return [[int(m[1]), int(m[2]), int(m[3])]
|
|
for m in
|
|
re.finditer(r'x=(-?\d+).*y=(-?\d+).*z=(-?\d+)', fp.read())]
|
|
|
|
|
|
def test_day12a():
|
|
moons = [(m, [0, 0, 0]) for m in get_moons()]
|
|
e = 0
|
|
for _ in range(1000):
|
|
for me, other in permutations(moons, 2):
|
|
v = me[1]
|
|
pa = me[0]
|
|
pb = other[0]
|
|
v[0] += -1 if pa[0] > pb[0] else 1 if pa[0] < pb[0] else 0
|
|
v[1] += -1 if pa[1] > pb[1] else 1 if pa[1] < pb[1] else 0
|
|
v[2] += -1 if pa[2] > pb[2] else 1 if pa[2] < pb[2] else 0
|
|
for moon in moons:
|
|
moon[0][0] += moon[1][0]
|
|
moon[0][1] += moon[1][1]
|
|
moon[0][2] += moon[1][2]
|
|
|
|
for p, v in moons:
|
|
e += (abs(p[0])+abs(p[1])+abs(p[2]))*(abs(v[0])+abs(v[1])+abs(v[2]))
|
|
|
|
assert e == 9139
|
|
|
|
|
|
def test_day12b():
|
|
"""
|
|
Finished with helpful hints from ZuBsPaCe
|
|
https://www.reddit.com/r/adventofcode/comments/e9jxh2/help_2019_day_12_part_2_what_am_i_not_seeing/far9cgu/
|
|
"""
|
|
moons = [[m, [0, 0, 0]] for m in get_moons()]
|
|
com = []
|
|
for i in range(3):
|
|
count = 0
|
|
initial = deepcopy(moons)
|
|
while True:
|
|
for me, other in permutations(moons, 2):
|
|
pa = me[0]
|
|
pb = other[0]
|
|
me[1][i] += -1 if pa[i] > pb[i] else 1 if pa[i] < pb[i] else 0
|
|
for moon in moons:
|
|
moon[0][i] += moon[1][i]
|
|
count += 1
|
|
if moons == initial:
|
|
break
|
|
com.append(count)
|
|
steps = reduce(lambda a, b: int(a * b / gcd(a, b)), com)
|
|
assert steps == 420788524631496
|
|
|