Add Day 7 solution.
This commit is contained in:
69
day7/solver.py
Normal file
69
day7/solver.py
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
"""
|
||||||
|
Bit tired and lazy today.
|
||||||
|
|
||||||
|
Just going to go for minimal effort.
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
|
||||||
|
test_data = r"""
|
||||||
|
190: 10 19
|
||||||
|
3267: 81 40 27
|
||||||
|
83: 17 5
|
||||||
|
156: 15 6
|
||||||
|
7290: 6 8 6 15
|
||||||
|
161011: 16 10 13
|
||||||
|
192: 17 8 14
|
||||||
|
21037: 9 7 18 13
|
||||||
|
292: 11 6 16 20
|
||||||
|
"""
|
||||||
|
|
||||||
|
def load_data(data):
|
||||||
|
for line in data.splitlines():
|
||||||
|
if line := line.strip():
|
||||||
|
target, remaining = line.split(': ')
|
||||||
|
yield int(target), tuple(map(int, remaining.split()))
|
||||||
|
|
||||||
|
|
||||||
|
def validate(target, parts, current=None, ors=False):
|
||||||
|
if not parts:
|
||||||
|
return target == current
|
||||||
|
part, remaining = parts[0], parts[1:]
|
||||||
|
|
||||||
|
if current is None:
|
||||||
|
valid = validate(target, remaining, part, ors=ors)
|
||||||
|
elif current > target:
|
||||||
|
valid = False
|
||||||
|
else:
|
||||||
|
# Try mul first
|
||||||
|
valid = validate(target, remaining, current * part, ors=ors)
|
||||||
|
valid = valid or validate(target, remaining, current + part, ors=ors)
|
||||||
|
if ors:
|
||||||
|
valid = valid or validate(target, remaining, int(str(current)+str(part)), ors=ors)
|
||||||
|
return valid
|
||||||
|
|
||||||
|
|
||||||
|
def valid_sums(data, **kwargs):
|
||||||
|
return sum(target for target, parts in load_data(data) if validate(target, parts, **kwargs))
|
||||||
|
|
||||||
|
|
||||||
|
def test_a():
|
||||||
|
print("Testing")
|
||||||
|
assert valid_sums(test_data) == 3749
|
||||||
|
print("Tested")
|
||||||
|
|
||||||
|
def test_b():
|
||||||
|
print("Testing")
|
||||||
|
assert valid_sums(test_data, ors=True) == 11387
|
||||||
|
print("Tested")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_a()
|
||||||
|
with open(sys.argv[1]) as f:
|
||||||
|
data = f.read()
|
||||||
|
print(f"Sum is {valid_sums(data)}")
|
||||||
|
test_b()
|
||||||
|
print(f"New Sum is {valid_sums(data, ors=True)}")
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user