Do day 7 RTL

That does indeed cut down branching significantly
This commit is contained in:
2024-12-09 22:21:12 +01:00
parent cb7aedc4ba
commit d49fc8e769

View File

@@ -11,35 +11,39 @@ def parse_input(input: str) -> tuple[int, list[int]]:
return result return result
def is_possible(target: int, nums: list[int], cur: int) -> bool: def is_possible(target: int, nums: list[int]) -> bool:
if cur == target and not nums: if target == 0:
return True return not nums
if not nums or target < 0:
if cur > target or not nums:
return False return False
head = nums[0] tail = nums[-1]
remainder = nums[1:] remainder = nums[:-1]
return is_possible(target, remainder, cur + head) or is_possible( return is_possible(target - tail, remainder) or (
target, remainder, cur * head target % tail == 0 and is_possible(target // tail, remainder)
) )
def is_possible2(target: int, nums: list[int], cur: int) -> bool: def is_possible2(target: int, nums: list[int]) -> bool:
if cur == target and not nums: if target == 0:
return True return not nums
if not nums or target < 0:
if cur > target or not nums:
return False return False
head = nums[0] tail = nums[-1]
remainder = nums[1:] remainder = nums[:-1]
target_str = str(target)
tail_str = str(tail)
return ( return (
is_possible2(target, remainder, cur + head) is_possible2(target - tail, remainder)
or is_possible2(target, remainder, cur * head) or (target % tail == 0 and is_possible2(target // tail, remainder))
or is_possible2(target, remainder, int(f"{cur}{head}")) or (
target_str.endswith(tail_str)
and is_possible2(int(target_str[: -len(str(tail_str))]), remainder)
)
) )
@@ -48,14 +52,10 @@ class DayRunner(SeparateRunner):
def part1(cls, input: str) -> int: def part1(cls, input: str) -> int:
lines = parse_input(input) lines = parse_input(input)
return sum( return sum(target for target, nums in lines if is_possible(target, nums))
target for target, nums in lines if is_possible(target, nums[1:], nums[0])
)
@classmethod @classmethod
def part2(cls, input: str) -> int: def part2(cls, input: str) -> int:
lines = parse_input(input) lines = parse_input(input)
return sum( return sum(target for target, nums in lines if is_possible2(target, nums))
target for target, nums in lines if is_possible2(target, nums[1:], nums[0])
)