|
1 | 1 | using AdventOfCode.Common; |
2 | 2 |
|
3 | | -var lines = Resources.GetInputFileLines(); |
| 3 | +var equations = Resources.GetInputFileLines() |
| 4 | + .Select(line => line.SplitBy(": ")) |
| 5 | + .Select(parts => new Equation(ulong.Parse(parts[0]), [.. parts[1].Split(' ').Select(ulong.Parse)])) |
| 6 | + .ToArray(); |
4 | 7 |
|
5 | | -Console.WriteLine($"Part 1: {""}"); |
6 | | -Console.WriteLine($"Part 2: {""}"); |
| 8 | +var validEquations = equations |
| 9 | + .Where(equation => equation.IsValid(useConcatenation: false)) |
| 10 | + .Select(equation => equation.Target) |
| 11 | + .ToList(); |
| 12 | + |
| 13 | +var total = validEquations |
| 14 | + .Sum(); |
| 15 | + |
| 16 | +var totalWithConcatenation = equations |
| 17 | + .Where(e => !validEquations.Contains(e.Target)) |
| 18 | + .Where(e => e.IsValid(useConcatenation: true)) |
| 19 | + .Select(equation => equation.Target) |
| 20 | + .Sum(); |
| 21 | + |
| 22 | +Console.WriteLine($"Part 1: {total}"); |
| 23 | +Console.WriteLine($"Part 2: {total + totalWithConcatenation}"); |
| 24 | + |
| 25 | +file record Equation(ulong Target, ulong[] Operands) |
| 26 | +{ |
| 27 | + public bool IsValid(bool useConcatenation) |
| 28 | + => IsValid(useConcatenation, 0, 0); |
| 29 | + |
| 30 | + private bool IsValid(bool useConcatenation, ulong acc, int index) |
| 31 | + { |
| 32 | + if (index == Operands.Length) return acc == Target; |
| 33 | + if (acc > Target) return false; |
| 34 | + |
| 35 | + return IsValid(useConcatenation, Math.Max(acc, 1) * Operands[index], index + 1) |
| 36 | + || IsValid(useConcatenation, acc + Operands[index], index + 1) |
| 37 | + || (useConcatenation && IsValid(true, Concatenate(acc, Operands[index]), index + 1)); |
| 38 | + } |
| 39 | + |
| 40 | + // 1000 with as many zeros as a base-10 log (and account for '0') |
| 41 | + private static ulong Concatenate(ulong first, ulong second) |
| 42 | + => first * (ulong)Math.Max(10, Math.Pow(10, Math.Ceiling(Math.Log10(second)))) + second; |
| 43 | +} |
0 commit comments