Skip to content

Commit

Permalink
AoC2024.7 Extract operand logic
Browse files Browse the repository at this point in the history
  • Loading branch information
loociano committed Dec 7, 2024
1 parent e8a12f6 commit ba40b66
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions aoc2024/src/day07/python/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@
# 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 typing import Callable, Sequence
from itertools import product

_OPERATORS: dict[str, Callable] = {
'+': lambda a, b: a + b,
'*': lambda a, b: a * b,
'||': lambda a, b: int(str(a) + str(b))
}


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."""
Expand All @@ -26,23 +32,20 @@ def _could_be_true(equation_data: str, operators: tuple[str, ...]) -> int | None
operators_queue = list(combination)
computation = operands_queue.pop(0)
while len(operands_queue):
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))
computation = _OPERATORS.get(operators_queue.pop(0))(computation, operands_queue.pop(0))
if computation > result:
break # All operands increase computation so we can leave early.
if computation == result:
return result
return None


def calc_calibration(equations: Sequence[str], operators: tuple[str, ...] = ('+', '*')) -> int:
def calc_calibration(
equations: Sequence[str],
operators: tuple[str, ...] = ('+', '*')) -> int:
"""Returns the total calibration result, which is the sum of the equations that
can be made true with some combination of operators."""
total_calibration = 0
for equation_data in equations:
result = _could_be_true(equation_data, operators)
Expand Down

0 comments on commit ba40b66

Please sign in to comment.