-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart1.py
60 lines (47 loc) · 1.42 KB
/
part1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import re
from typing import NamedTuple
VECTOR_RE = re.compile(r'-?\d+')
class Vector(NamedTuple):
x: int
y: int
z: int
def add(self, other):
return self._replace(
x=self.x + other.x,
y=self.y + other.y,
z=self.z + other.z,
)
class Moon(NamedTuple):
pos: Vector
vel: Vector
with open("input.txt", "r") as f:
data = f.read().splitlines()
moons = []
for d in data:
x, y, z = VECTOR_RE.findall(d)
moons.append(Moon(Vector(int(x), int(y), int(z)), Vector(0, 0, 0)))
for _ in range(1000):
for i, moon in enumerate(moons):
vel_x, vel_y, vel_z = moon.vel
for next_moon in moons:
if next_moon is moon:
continue
if next_moon.pos.x > moon.pos.x:
vel_x += 1
elif next_moon.pos.x < moon.pos.x:
vel_x -= 1
if next_moon.pos.y > moon.pos.y:
vel_y += 1
elif next_moon.pos.y < moon.pos.y:
vel_y -= 1
if next_moon.pos.z > moon.pos.z:
vel_z += 1
elif next_moon.pos.z < moon.pos.z:
vel_z -= 1
moons[i] = moon._replace(vel=Vector(vel_x, vel_y, vel_z))
for i, moon in enumerate(moons):
moons[i] = moon._replace(pos=moon.pos.add(moon.vel))
print(sum(
sum(abs(p) for p in moon.pos) * sum(abs(v) for v in moon.vel)
for moon in moons
))