AdventOfCode/2019/day12.py

41 lines
1.1 KiB
Python
Raw Normal View History

2019-12-12 19:25:46 +01:00
import itertools
import re
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-12 22:42:39 +01:00
coords = [list([int(i) for i in match.groups()]) for match in matches]
moons = [[coord, [0] * 3] for coord in coords]
# Part 1
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
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()