Advertisement
mgla

Advent of Code 2024 - Day 7

Dec 7th, 2024 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.66 KB | None | 0 0
  1. var timer = System.Diagnostics.Stopwatch.StartNew();
  2. var input = await File.ReadAllLinesAsync("input.txt");
  3.  
  4. var equations = new List<(long Target, long[] Values)>();
  5.  
  6. foreach (var line in input)
  7. {
  8.     var split = line.Split(": ");
  9.     var targetValue = long.Parse(split[0]);
  10.     var values = split[1].Split(' ').Select(long.Parse).ToArray();
  11.  
  12.     equations.Add((targetValue, values));
  13. }
  14.  
  15. Console.WriteLine($"Parsing done. ({timer.ElapsedMilliseconds}ms)");
  16.  
  17. var part1 = equations.Where(equation => IsValid(equation.Target, 0, 0, equation.Values))
  18.     .Sum(equation => equation.Target);
  19.  
  20. Console.WriteLine($"Part 1: {part1} ({timer.ElapsedMilliseconds}ms)");
  21.  
  22. var part2 = equations.Where(equation => IsValid(equation.Target, 0, 0, equation.Values, true))
  23.     .Sum(equation => equation.Target);
  24.  
  25. Console.WriteLine($"Part 2: {part2} ({timer.ElapsedMilliseconds}ms)");
  26.  
  27. return;
  28.  
  29. bool IsValid(long targetValue, long currentValue, int index, long[] values, bool isPart2 = false)
  30. {
  31.     if (index == values.Length)
  32.     {
  33.         return currentValue == targetValue;
  34.     }
  35.  
  36.     if (currentValue > targetValue)
  37.     {
  38.         return false;
  39.     }
  40.  
  41.     var result = IsValid(targetValue, currentValue + values[index], index + 1, values, isPart2) ||
  42.                  IsValid(targetValue, currentValue * values[index], index + 1, values, isPart2);
  43.  
  44.     if (!isPart2 || result) return result;
  45.  
  46.     var concat = Concat(currentValue, values[index]);
  47.  
  48.     result = IsValid(targetValue, concat, index + 1, values, true);
  49.  
  50.     return result;
  51. }
  52.  
  53. static long Concat(long a, long b)
  54. {
  55.     var pow = (int)Math.Log10(b) + 1;
  56.     return a * (long)Math.Pow(10, pow) + b;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement