DEV Community

Cover image for AoC '24 - Day7: Bridge Repair
Grant Riordan
Grant Riordan

Posted on

AoC '24 - Day7: Bridge Repair

Day 7: Bridge Repair

For this solution, I found the best way was using recursion.

What is Recursion?

Recursion is when a function calls itself to solve smaller parts of a problem. It's like solving a big puzzle by breaking it into smaller, identical puzzles. Each time the function calls itself, it works on a smaller piece of the original problem.

How Does Recursion Work?

Recursion has two main parts:

Base Case:

This is when the recursion stops. It's the simplest possible version of the problem. Think of it as the "goalpost." Once reached, the function stops calling itself and starts returning results.

In our case this is when the index == length of the equation parameters.

Recursive Case:

This is when the function calls itself to work on a smaller piece of the problem.

It's like taking a step closer to the base case each time.

How Does the Puzzle Use Recursion?

In the puzzle, the goal is to check if a target number can be made by applying operators (+, *, ||) between a series of numbers.

Here’s the challenge:

Try applying + between the current number and the next.
Try applying * between the current number and the next.
Try combining the two numbers using || (concatenation).

Continue this process until either:

All numbers are used, and the result equals the target (Base Case)
or
All possibilities are explored without finding a match (Recursive Case)

You can find the solution in both Python & C# here

As always feel free to follow me on twitter for more tips, solutions, articles & blog posts across multiple media.

Top comments (0)