From fb4008682185abcc253fc34c314ba5a9e8a12f49 Mon Sep 17 00:00:00 2001 From: Holly McFarland Date: Wed, 11 Dec 2024 17:33:54 -0500 Subject: [PATCH] day 7 --- day_07/part_a.py | 32 ++++++++++++++++++++++++++++++++ day_07/part_b.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 day_07/part_a.py create mode 100644 day_07/part_b.py diff --git a/day_07/part_a.py b/day_07/part_a.py new file mode 100644 index 0000000..5571de9 --- /dev/null +++ b/day_07/part_a.py @@ -0,0 +1,32 @@ +import aocd + +def get_calibrations(data): + for line in data.split('\n'): + target, *operands = line.replace(':', '').split() + yield int(target), tuple(int(n) for n in operands) + +def can_produce_target(target, operands, current=0): + # Base case, we're out of numbers to apply + if not operands: + return target == current + + # We've gone too high + if current > target: + return False + + return can_produce_target(target, operands[1:], current + operands[0]) \ + or can_produce_target(target, operands[1:], current * operands[0]) + +def solve(data): + return sum(target*can_produce_target(target, operands) for target, operands in get_calibrations(data)) + +if __name__ == '__main__': + puz = aocd.models.Puzzle(year=2024, day=7) + + # data = puz.examples[0].input_data + data = puz.input_data + + solution = solve(data) + + print(solution) + aocd.submit(solution, year=2024, day=7, part='a') \ No newline at end of file diff --git a/day_07/part_b.py b/day_07/part_b.py new file mode 100644 index 0000000..0918147 --- /dev/null +++ b/day_07/part_b.py @@ -0,0 +1,34 @@ +import aocd +import math + +def get_calibrations(data): + for line in data.split('\n'): + target, *operands = line.replace(':', '').split() + yield int(target), tuple(int(n) for n in operands) + +def can_produce_target(target, operands, current=0): + # Base case, we're out of numbers to apply + if not operands: + return target == current + + # We've gone too high + if current > target: + return False + + return can_produce_target(target, operands[1:], current + operands[0]) \ + or can_produce_target(target, operands[1:], current * operands[0]) \ + or can_produce_target(target, operands[1:], current * 10**math.floor(math.log(operands[0], 10) + 1) + operands[0]) + +def solve(data): + return sum(target*can_produce_target(target, operands) for target, operands in get_calibrations(data)) + +if __name__ == '__main__': + puz = aocd.models.Puzzle(year=2024, day=7) + + # data = puz.examples[0].input_data + data = puz.input_data + + solution = solve(data) + + print(solution) + aocd.submit(solution, year=2024, day=7, part='b') \ No newline at end of file