Advent Of Code Day 10: Backtracking and Dynamic Programming

Howdy Everyone,

Catching up on the Advent of Code, I got to day 10 today, here it is: Day 10 - Advent of Code 2020.


Description is a little long and tedious but in the end you get the gist of it. Part 1 is looking for a simple path from 0 to max. I looked at the input size and it did not seem that large, so I thought backtracking would do the trick. Indeed a simple straightforward DFS backtracking from 0 to max works. Part 2 asks for the count of ALL paths. That's a little tricky, especially after reading this part of the description:

You glance back down at your bag and try to remember why you brought so many adapters; there must be more than a trillion valid ways to arrange them! Surely, there must be an efficient way to count the arrangements.

That should give you the hint that the "adventers" are looking for a Dynamic Programming (DP) solution. Luckily, this DP is super simple, and the way that I like to implement DP is by construction from 0..max. Basically I start solving the problems for n=0, 1, 2, ..., max, using previously solved (and stored) solutions. Also worked well. Make sure to use a long for your DP solution storage as the number of paths will grow rather quickly. Code is below, cheers, ACC.

static void Main(string[] args)
{
 FileInfo fi = new FileInfo("input.txt");
 StreamReader sr = fi.OpenText();
 Hashtable volts = new Hashtable();
 int max = 0;
 while (!sr.EndOfStream)
 {
 string str = sr.ReadLine().Trim();
 if (!String.IsNullOrEmpty(str))
 {
 int n = Int32.Parse(str);
 max = Math.Max(max, n);
 volts.Add(n, true);
 }
 }
 sr.Close();
 int[] diff = new int[4]; //Ignore diff[0]
 int totalUsed = 0;
 if (AdaptationPartOne(volts, 0, ref totalUsed, ref diff))
 {
 Console.WriteLine("Found a path!");
 for (int i = 1; i <= 3; i++)
 {
 Console.WriteLine("Diff of {0}: {1}", i, diff[i]);
 }
 long sol = diff[1];
 sol *= diff[3];
 Console.WriteLine("Solution: {0}", sol);
 }
 else
 {
 Console.WriteLine("Not path found!");
 }
 long sol2 = AdaptationPartTwo(volts, max);
 Console.WriteLine("Number of combinations: {0}", sol2);
}
public static long AdaptationPartTwo(Hashtable volts,
 int max)
{
 if (!volts.ContainsKey(0)) volts.Add(0, true);
 long[] dp = new long[max + 1];
 dp[0] = 1;
 for (int i = 1; i <= max; i++)
 {
 if (volts.ContainsKey(i))
 {
 for (int d = 1; d <= 3; d++)
 {
 if (i - d >= 0)
 {
 dp[i] += dp[i - d];
 }
 }
 }
 }
 return dp[max];
}
public static bool AdaptationPartOne(Hashtable volts,
 int currentVoltage,
 ref int totalUsed,
 ref int[] diff)
{
 if (totalUsed == volts.Count)
 {
 //Account for the last device...
 diff[3]++;
 return true;
 }
 for (int i = 1; i <= 3; i++)
 {
 int next = currentVoltage + i;
 if (volts.ContainsKey(next) && (bool)volts[next])
 {
 volts[next] = false;
 diff[i]++;
 totalUsed++;
 if (AdaptationPartOne(volts, next, ref totalUsed, ref diff)) return true;
 totalUsed--;
 diff[i]--;
 volts[next] = true;
 }
 }
 return false;
}

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...