Skip to content

Commit

Permalink
AoC2024 day 7 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
loociano committed Dec 7, 2024
1 parent c7bd179 commit 0fcf749
Show file tree
Hide file tree
Showing 8 changed files with 946 additions and 0 deletions.
Empty file added aoc2024/src/day07/__init__.py
Empty file.
Empty file.
49 changes: 49 additions & 0 deletions aoc2024/src/day07/python/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Sequence
from itertools import product


def _could_be_true(equation_data: str, operators: tuple[str, ...]) -> int | None:
"""Returns equation result if it can be made true with some combination of addition and multiplication."""
result, operands = equation_data.split(': ')
result = int(result)
operands = operands.split()
combinations = list(product(operators, repeat=len(operands) - 1))
for combination in combinations:
operands_queue = list(map(int, operands))
operators_queue = list(combination)
computation = operands_queue.pop(0)
while len(operands_queue) and computation < result:
next_operand = operands_queue.pop(0)
next_operator = operators_queue.pop(0)
# Cannot use eval() because it follows math precedence rules.
if next_operator == '+':
computation += next_operand
if next_operator == '*':
computation *= next_operand
if next_operator == '||':
computation = int(str(computation) + str(next_operand))
if computation == result:
return result
return None


def calc_calibration(equations: Sequence[str], operators: tuple[str, ...] = ('+', '*')) -> int:
total_calibration = 0
for equation_data in equations:
result = _could_be_true(equation_data, operators)
if result is not None:
total_calibration += result
return total_calibration
Empty file added aoc2024/test/day07/__init__.py
Empty file.
Empty file.
9 changes: 9 additions & 0 deletions aoc2024/test/day07/python/example1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
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
Loading

0 comments on commit 0fcf749

Please sign in to comment.