-
Notifications
You must be signed in to change notification settings - Fork 0
/
day14.py
executable file
·75 lines (63 loc) · 2.18 KB
/
day14.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
71
72
73
import numpy as np
# parse interactions and put in dict
f = open('input14.txt','r')
txt = f.read()
txt = txt.split('\n')
txt = txt[:-1]
txt = [item.split(' => ') for item in txt]
txt = [[item[0].split(', '), item[1]] for item in txt]
interactions = {}
for item in txt:
res = item[1].split(' ')[1]
res_num = int(item[1].split(' ')[0])
interactions[res] = {'self': res_num}
for item2 in item[0]:
cur = item2.split(' ')[1]
cur_num = int(item2.split(' ')[0])
interactions[res][cur] = cur_num
spare_elements = {}
for key in interactions:
spare_elements[key] = 0
spare_elements['ORE'] = 0
spare_elements_start = spare_elements.copy()
def cnt_ore(element, num, spare_elements):
if num == 0:
return 0, spare_elements
elif element == 'ORE':
return num
elif spare_elements[element] >= num:
spare_elements[element] -= num
return 0
elif spare_elements[element] > 0:
tmp = spare_elements[element]
spare_elements[element] = 0
return cnt_ore(element, num - tmp, spare_elements)
else:
cnt = 0
if num <= interactions[element]['self']:
rep = 1
spare_elements[element] = (interactions[element]['self'] - num)
else:
rep = int(np.ceil(num/interactions[element]['self']))
spare_elements[element] = (rep*interactions[element]['self'] - num)
for i in range(rep):
for key in interactions[element]:
if key == 'self':
continue
cnt += cnt_ore(key, interactions[element][key], spare_elements)
return cnt
# Part 1:
print('part 1 answer = ' + str(cnt_ore('FUEL', 1, spare_elements)))
def cnt_ore_exact(element, num):
if element=='ORE':
return num
else:
cnt = 0
for key in interactions[element]:
if key == 'self':
continue
cnt += (num/interactions[element]['self'])*cnt_ore_exact(key, interactions[element][key])
return cnt
# Part 2:
# calculate the 'exact' OREs needed to produce 1 fuel, and divide
print('part 2 answer = ' + str(int((10**12)/cnt_ore_exact('FUEL', 1))-1))