-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday_12.py
More file actions
51 lines (41 loc) · 1.66 KB
/
day_12.py
File metadata and controls
51 lines (41 loc) · 1.66 KB
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
#%%
import math
import re
def simulate(positions, velocities, steps=math.inf):
initial_positions = positions.copy()
initial_velocities = velocities.copy()
step = 0
while step < steps and (
step == 0 or positions != initial_positions or velocities != initial_velocities
):
for i in range(len(positions)):
velocities[i] += sum(
1 if positions[i] < position else -1
for position in positions
if position != positions[i]
)
for i in range(len(positions)):
positions[i] += velocities[i]
step += 1
return step
def part1(positions):
px, vx = [x for x, _, _ in positions], [0] * len(positions)
py, vy = [y for _, y, _ in positions], [0] * len(positions)
pz, vz = [z for _, _, z in positions], [0] * len(positions)
for p, v in zip((px, py, pz), (vx, vy, vz)):
simulate(p, v, 1000)
return sum(
(abs(px[i]) + abs(py[i]) + abs(pz[i])) * (abs(vx[i]) + abs(vy[i]) + abs(vz[i]))
for i in range(len(positions))
)
def part2(positions):
def lcm(a, b):
return a * b // math.gcd(a, b)
x_repeat = simulate([x for x, _, _ in positions], [0] * len(positions))
y_repeat = simulate([y for _, y, _ in positions], [0] * len(positions))
z_repeat = simulate([z for _, _, z in positions], [0] * len(positions))
return lcm(lcm(x_repeat, y_repeat), z_repeat)
with open("day_12.input") as input_data:
positions = [list(map(int, re.findall(r"\-?\d+", l))) for l in input_data]
print(f"Part 1: Total energy is {part1(positions)}")
print(f"Part 2: State repeating after {part2(positions)} iterations")