Skip to content

Commit 7a0a7f9

Browse files
committed
Day 9
1 parent 67826b6 commit 7a0a7f9

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

day9/day9.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
def is_all_zeros(array):
2+
return all(v == 0 for v in array)
3+
4+
5+
def find_differences(history):
6+
diffs = [history]
7+
while not is_all_zeros(diffs[-1]):
8+
previous = diffs[-1]
9+
diff = []
10+
for i in range(len(previous)-1):
11+
diff.append(previous[i+1] - previous[i])
12+
diffs.append(diff)
13+
return diffs
14+
15+
16+
def extrapolate_last(diffs):
17+
extrapolated = [0]
18+
for i in range(len(diffs)-2, -1, -1):
19+
extrapolated.append(diffs[i][-1] + extrapolated[-1])
20+
return extrapolated[-1]
21+
22+
23+
def extrapolate_first(diffs):
24+
extrapolated = [0]
25+
for i in range(len(diffs)-2, -1, -1):
26+
extrapolated.append(diffs[i][0] - extrapolated[-1])
27+
return extrapolated[-1]
28+
29+
30+
def part1(histories):
31+
result = sum([extrapolate_last(find_differences(history)) for history in histories])
32+
print(f"Result part 1: {result}")
33+
34+
35+
def part2(histories):
36+
result = sum([extrapolate_first(find_differences(history)) for history in histories])
37+
print(f"Result part 2: {result}")
38+
39+
40+
def read_data_from_file(filename):
41+
histories = []
42+
with open(filename) as file:
43+
for line in file:
44+
line_string = line.rstrip()
45+
split = line_string.split()
46+
histories.append([int(value) for value in split])
47+
return histories
48+
49+
50+
# histories = read_data_from_file("testinput.txt")
51+
histories = read_data_from_file("input.txt")
52+
53+
part1(histories)
54+
part2(histories)

0 commit comments

Comments
 (0)