Add day 11

This commit is contained in:
2025-01-24 10:19:12 +01:00
parent d839ab7ec9
commit 6e433fcf3d
2 changed files with 128 additions and 0 deletions

127
Days/Day11.cs Normal file
View File

@@ -0,0 +1,127 @@
using System.Collections.Frozen;
using System.Numerics;
using Spectre.Console;
namespace AdventOfCode.Days;
public class Day11 : Day
{
public override int Number => 11;
public override string Name => "Plutonian Pebbles";
private const int BlinkIterations = 25;
public override void RunPart1(bool display = true)
{
var stones = ParseStones();
for (var iteration = 0; iteration < BlinkIterations; iteration++)
{
var index = 0;
while (index < stones.Count)
{
var stone = stones[index];
var stoneString = stone.ToString();
if (stone is 0)
{
stones[index] = 1;
}
else if (stoneString.Length % 2 == 0)
{
var splitIndex = stoneString.Length / 2;
var leftStone = long.Parse(stoneString[..splitIndex]);
var rightStone = long.Parse(stoneString[splitIndex..]);
stones[index] = leftStone;
stones.Insert(index + 1, rightStone);
index++;
}
else
{
stones[index] = stone * 2024;
}
index++;
}
}
if (display)
{
AnsiConsole.MarkupLine($"[green]Number of stones after blinking {BlinkIterations} times: [yellow]{stones.Count}[/][/]");
}
}
public override void RunPart2(bool display = true)
{
var stones = ParseStones().ToDictionary(s => s, _ => 1L);
for (var iteration = 0; iteration < (BlinkIterations * 3); iteration++)
{
var stonesToIterate = stones.ToList();
foreach (var (stone, count) in stonesToIterate)
{
var stoneString = stone.ToString();
if (stone is 0)
{
SafeAdd(stones, 1, count);
}
else if (stoneString.Length % 2 == 0)
{
var splitIndex = stoneString.Length / 2;
var leftStone = long.Parse(stoneString[..splitIndex]);
var rightStone = long.Parse(stoneString[splitIndex..]);
SafeAdd(stones, leftStone, count);
SafeAdd(stones, rightStone, count);
}
else
{
SafeAdd(stones, stone * 2024, count);
}
SafeAdd(stones, stone, -count);
}
}
var stonesCount = stones.Sum(p => p.Value);
if (display)
{
AnsiConsole.MarkupLine($"[green]Number of stones after blinking {BlinkIterations} times: [yellow]{stonesCount}[/][/]");
}
}
private List<long> ParseStones()
{
var stones = new List<long>();
var span = Input.AsSpan();
foreach (var stoneRange in span.Split(' '))
{
stones.Add(long.Parse(span[stoneRange]));
}
return stones;
}
private void SafeAdd(Dictionary<long, long> dictionary, long key, long valueToAdd)
{
if (dictionary.TryGetValue(key, out var currentValue))
{
dictionary[key] = currentValue + valueToAdd;
}
else
{
dictionary[key] = valueToAdd;
}
}
}

1
Inputs/Day11.txt Normal file
View File

@@ -0,0 +1 @@
0 7 6618216 26481 885 42 202642 8791