Skip to content

Commit

Permalink
day 11 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
KaterynaKateryna committed Dec 12, 2024
1 parent f2e0646 commit 3b4bff1
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions AdventOfCode/Day11.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@ public override ValueTask<string> Solve_2()
{
List<long> stones = GetInput();

for (int i = 0; i < 35; ++i) // TODO make work for 75
{
stones = Blink(stones);
}
Dictionary<long,Dictionary<int, long>> cache = new Dictionary<long, Dictionary<int, long>>();

return new(stones.Count.ToString());
long result = BlinkRecursive(stones, 75, cache);

return new(result.ToString());
}

private List<long> Blink(List<long> stones)
Expand Down Expand Up @@ -71,30 +70,42 @@ private List<long> GetInput()

#region recursive

private long BlinkRecursive(List<long> stones, int times)
private long BlinkRecursive(List<long> stones, int times, Dictionary<long, Dictionary<int, long>> cache)
{
long result = 0;
for (int i = 0; i < stones.Count; i++)
{
result += BlinkRecursive(stones[i], times);
result += BlinkRecursive(stones[i], times, cache);
}
return result;
}

private long BlinkRecursive(long stone, int times)
private long BlinkRecursive(long stone, int times, Dictionary<long, Dictionary<int, long>> cache)
{
if (cache.TryGetValue(stone, out var hits))
{
if (hits.TryGetValue(times, out long cachedResult))
{
return cachedResult;
}
}

(long a, long? b) = Blink(stone);

if (times == 1)
{
return b.HasValue ? 2 : 1;
}

long result = BlinkRecursive(a, times - 1);
long result = BlinkRecursive(a, times - 1, cache);
if (b.HasValue)
{
result += BlinkRecursive(b.Value, times - 1);
result += BlinkRecursive(b.Value, times - 1, cache);
}

cache.TryAdd(stone, new Dictionary<int, long>());
cache[stone][times] = result;

return result;
}

Expand Down

0 comments on commit 3b4bff1

Please sign in to comment.