-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day_09.py
70 lines (53 loc) · 1.49 KB
/
Day_09.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
61
62
63
64
65
66
67
68
69
70
# -*- coding: utf-8 -*-
"""
Advent of Code 2023, Day 9
https://adventofcode.com/2023/day/9
2023-12-09, 11:36; 2023-12-09, 11:43
"""
### Load Data #################################################################
# read input
filename = 'Day_09.txt'
f = open(filename)
text = f.readlines()
# example input
# text = ['0 3 6 9 12 15', \
# '1 3 6 10 15 21', \
# '10 13 16 21 30 45']
# difference function
def diff(nums):
diffs = [nums[i+1]-nums[i] for i in range(len(nums)-1)]
return diffs
### Part One ##################################################################
# analyze data
my_sum = 0
for line in text:
# calculate differences
diffs = []
nums = [int(s) for s in line.split()]
diffs.append(nums)
while not all([n==0 for n in nums]):
nums = diff(nums)
diffs.append(nums)
# predict next value
number = sum([diffs[i][-1] for i in range(len(diffs)-1,-1,-1)])
my_sum = my_sum + number
# output result
print(my_sum)
### Part Two ##################################################################
# analyze data
my_sum = 0
for line in text:
# calculate differences
diffs = []
nums = [int(s) for s in line.split()]
diffs.append(nums)
while not all([n==0 for n in nums]):
nums = diff(nums)
diffs.append(nums)
# predict first value
number = 0
for i in range(len(diffs)-1,-1,-1):
number = diffs[i][0] - number
my_sum = my_sum + number
# output result
print(my_sum)