mirror of
https://github.com/parnic/advent-of-code-2024.git
synced 2025-06-16 20:40:14 -05:00
Okay, this optimization was easier than I thought it'd be. I started by not building a new list every time I wanted to operate on the next value since that seemed like low-hanging fruit. That helped, but not as much as I expected (as is always the case with optimization, I feel). Next I ran this under a profiler and it showed that string concatenation was the biggest offender, so I found a way to do that without involving strings (it's a bit convoluted, but optimizations tend to do that...) and that cleaned up most of the problem. After that, getting the next element from the list was a (very minor) next-highest offender, so I cached that locally. Finally, on a whim I decided that the tuple wasn't helping me anymore, so I removed it and was surprised to see another 100ms or so disappear. I guess constructing those is worse than I thought...gotta file that away for later. I'm a little surprised that it didn't show up in the profiler (or I didn't know how to read it, perhaps).
61 lines
2.0 KiB
C#
61 lines
2.0 KiB
C#
using aoc2024.Util;
|
|
|
|
namespace aoc2024;
|
|
|
|
internal class Day07 : Day
|
|
{
|
|
private readonly List<(long result, List<long> inputs)> eqs = [];
|
|
internal override void Parse()
|
|
{
|
|
var lines = Util.Parsing.ReadAllLines($"{GetDay()}");
|
|
foreach (var line in lines)
|
|
{
|
|
var split = line.Split(':');
|
|
var nums = split[1].Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToList();
|
|
eqs.Add((long.Parse(split[0]), nums));
|
|
}
|
|
}
|
|
|
|
private static bool CanSolveAddMult(long target, long current, List<long> inputs, int idx)
|
|
{
|
|
if (idx == inputs.Count)
|
|
{
|
|
return current == target;
|
|
}
|
|
|
|
var next = inputs[idx];
|
|
var added = current + next;
|
|
var multd = current * next;
|
|
return CanSolveAddMult(target, added, inputs, idx + 1) ||
|
|
CanSolveAddMult(target, multd, inputs, idx + 1);
|
|
}
|
|
|
|
internal override string Part1()
|
|
{
|
|
long total = eqs.Where(eq => CanSolveAddMult(eq.result, eq.inputs[0], eq.inputs, 1)).Sum(eq => eq.result);
|
|
return $"Add | Mult calibration result: <+white>{total}";
|
|
}
|
|
|
|
private static bool CanSolveAddMultConcat(long target, long current, List<long> inputs, int idx)
|
|
{
|
|
if (idx == inputs.Count)
|
|
{
|
|
return current == target;
|
|
}
|
|
|
|
var next = inputs[idx];
|
|
var added = current + next;
|
|
var multd = current * next;
|
|
var cated = NumConcat.Longs(current, next);
|
|
return CanSolveAddMultConcat(target, added, inputs, idx + 1) ||
|
|
CanSolveAddMultConcat(target, multd, inputs, idx + 1) ||
|
|
CanSolveAddMultConcat(target, cated, inputs, idx + 1);
|
|
}
|
|
|
|
internal override string Part2()
|
|
{
|
|
long total = eqs.Where(eq => CanSolveAddMultConcat(eq.result, eq.inputs[0], eq.inputs, 1)).Sum(eq => eq.result);
|
|
return $"Add | Mult | Concat calibration result: <+white>{total}";
|
|
}
|
|
}
|