Advertisement
mgla

Advent of Code - 2024 - Day 11

Dec 11th, 2024 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.48 KB | None | 0 0
  1. var timer = System.Diagnostics.Stopwatch.StartNew();
  2. var stones = (await File.ReadAllTextAsync("input.txt")).Split(' ').ToDictionary(long.Parse, _ => 1L);
  3. Console.WriteLine($"Parsing complete. ({timer.ElapsedMilliseconds}ms)");
  4.  
  5. timer.Restart();
  6. Console.WriteLine($"Part 1: {CountStones(25, stones)} ({timer.ElapsedMilliseconds}ms)");
  7.  
  8. timer.Restart();
  9. Console.WriteLine($"Part 2: {CountStones(75, stones)} ({timer.ElapsedMilliseconds}ms)");
  10.  
  11. return;
  12.  
  13. static long CountStones(int iterations, Dictionary<long, long> stones)
  14. {
  15.     for (var i = 0; i < iterations; i++)
  16.     {
  17.         var newStones = new Dictionary<long, long>();
  18.  
  19.         foreach (var (stone, count) in stones)
  20.         {
  21.             var length = Math.Floor(Math.Log10(stone) + 1);
  22.  
  23.             if (stone == 0)
  24.             {
  25.                 AddStones(1, count);
  26.             }
  27.             else if (length % 2 == 0)
  28.             {
  29.                 var left = (long)(stone / Math.Pow(10, length / 2));
  30.                 var right = (long)(stone % Math.Pow(10, length / 2));
  31.  
  32.                 AddStones(left, count);
  33.                 AddStones(right, count);
  34.             }
  35.             else
  36.             {
  37.                 AddStones(stone * 2024, count);
  38.             }
  39.         }
  40.  
  41.         stones = newStones;
  42.         continue;
  43.  
  44.         void AddStones(long stone, long count)
  45.         {
  46.             newStones.TryAdd(stone, 0);
  47.             newStones[stone] += count;
  48.         }
  49.     }
  50.  
  51.     return stones.Values.Sum();
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement