-
Notifications
You must be signed in to change notification settings - Fork 0
/
day6.py
executable file
·58 lines (43 loc) · 1.19 KB
/
day6.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
#!/usr/bin/env python3
# [Day 6: Memory Reallocation](https://adventofcode.com/2017/day/6)
import sys
from pathlib import Path
filename = ("test.txt" if sys.argv[1] == "-t" else sys.argv[1]) if len(sys.argv) > 1 else "input.txt"
data = Path(filename).read_text().strip()
banks = list(map(int, data.split()))
size = len(banks)
seen = set()
iterations = 0
part1 = 0
part2 = 0
loop = None
while True:
state = ",".join(map(str, banks))
if state in seen:
# we have detected a loop
if part1 == 0:
part1 = iterations
loop = state
# count iterations within the first loop
elif loop == state:
part2 = iterations - part1
break
seen.add(state)
# find the max
blocks_max = -1
index_max = -1
for i, blocks in enumerate(banks):
if blocks_max < blocks:
index_max = i
blocks_max = blocks
assert blocks_max >= 1
# redistribute blocks
banks[index_max] = 0
realloc = max(1, blocks_max // size)
while blocks_max > 0:
index_max += 1
banks[index_max % size] += realloc
blocks_max -= realloc
iterations += 1
print(part1)
print(part2)