-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_7.py
82 lines (59 loc) · 2.1 KB
/
day_7.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
74
75
76
77
78
79
80
81
82
from utils import read_input
from itertools import product
def map_fn(line):
result, numbers = line.split(": ")
result = int(result)
numbers = [int(num) for num in numbers.split()]
return result, numbers
def is_solvable(result, numbers):
operators = ["*", "+"]
for operator_order in product(operators, repeat=len(numbers) - 1):
total = numbers[0]
for idx, num in enumerate(numbers[1:]):
if operator_order[idx - 1] == "+":
total += num
elif operator_order[idx - 1] == "*":
total *= num
if total > result:
break
if total == result:
return True
return False
def part_1():
equations = read_input(7, map_fn)
solvable = set()
for result, numbers in equations:
if is_solvable(result, numbers):
solvable.add((result, tuple(numbers)))
calibration_result = sum(res for res, _ in solvable)
print(f"Part 1: {calibration_result}")
assert calibration_result == 7885693428401
return solvable
def is_solvable_with_concatenation(result, numbers):
operators = ("*", "||", "+")
for operator_order in product(operators, repeat=len(numbers) - 1):
total = numbers[0]
for idx, num in enumerate(numbers[1:]):
if operator_order[idx - 1] == "+":
total += num
elif operator_order[idx - 1] == "*":
total *= num
elif operator_order[idx - 1] == "||":
total = int(f"{total}{num}")
if total > result:
break
if total == result:
return True
def part_2(solved):
equations = read_input(7, map_fn)
calibration_result = 0
for result, numbers in equations:
if (result, tuple(numbers)) in solved:
continue
if is_solvable_with_concatenation(result, numbers):
calibration_result += result
calibration_result += sum(r for r, _ in solved)
print(f"Part 2: {calibration_result}")
assert calibration_result == 348360680516005
solvable = part_1()
part_2(solvable)