AdventOfCode/2019/day12.py

62 lines
1.7 KiB
Python
Raw Normal View History

2019-12-13 09:00:10 +01:00
from copy import deepcopy
2019-12-12 19:25:46 +01:00
import itertools
import re
2019-12-13 09:00:10 +01:00
import numpy
2019-12-12 19:25:46 +01:00
def main():
with open("day12.txt", "rt") as input_file:
lines = input_file.readlines()
vector_re = re.compile(r"<x=(-?\d+), y=(-?\d+), z=(-?\d+)>")
matches = [vector_re.match(line.rstrip()) for line in lines]
2019-12-13 09:00:10 +01:00
coords = [[int(i) for i in match.groups()] for match in matches]
moons_i = [[coord, [0] * 3] for coord in coords]
2019-12-12 22:42:39 +01:00
# Part 1
2019-12-13 09:00:10 +01:00
moons = deepcopy(moons_i)
2019-12-12 19:25:46 +01:00
for _ in range(1000):
do_step(moons)
2019-12-12 22:42:39 +01:00
print("Total moons energy:", sum(get_energy(moon) for moon in moons))
2019-12-12 19:25:46 +01:00
2019-12-13 09:00:10 +01:00
# Part 2
d_cycles = [0] * 3
for d in range(3):
moons = deepcopy(moons_i)
step = 0
found_d_cycle = False
while not found_d_cycle:
do_step(moons)
step += 1
for moon, moon_i in zip(moons, moons_i):
if moon[0][d] != moon_i[0][d] or moon[1][d] != moon_i[1][d]:
break
else:
d_cycles[d] = step
found_d_cycle = True
print("Dimension cycles:", d_cycles)
print("LCM:", numpy.lcm.reduce(d_cycles))
2019-12-12 19:25:46 +01:00
def do_step(moons):
2019-12-12 22:42:39 +01:00
for a, b in itertools.combinations(moons, 2):
for d in range(3):
if a[0][d] > b[0][d]:
a[1][d] -= 1
b[1][d] += 1
elif a[0][d] < b[0][d]:
a[1][d] += 1
b[1][d] -= 1
2019-12-12 19:25:46 +01:00
for moon in moons:
2019-12-12 22:42:39 +01:00
for d in range(3):
moon[0][d] += moon[1][d]
def get_energy(moon):
pot = sum(abs(moon[0][d]) for d in range(3))
ket = sum(abs(moon[1][d]) for d in range(3))
return pot * ket
2019-12-12 19:25:46 +01:00
if __name__ == "__main__":
main()