Advertisement
mgla

Advent of Code 2023 - Day 15

Dec 15th, 2023
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. var input = File.ReadAllText("input.txt").Split(',');
  2.  
  3. var hashes = input.Select(Hash).ToList();
  4.  
  5. Console.WriteLine($"Part 1: {hashes.Sum()}");
  6.  
  7. var boxes = new List<List<(string Name, int FocalLength)>>();
  8. Enumerable.Range(0, 256).ToList().ForEach(_ => boxes.Add(new()));
  9. var separator = new[] { '=', '-' };
  10.  
  11. foreach (var step in input)
  12. {
  13.     var instructions = step.Split(separator, StringSplitOptions.RemoveEmptyEntries);
  14.     var lensName = instructions[0];
  15.     var box = boxes[Hash(lensName)];
  16.  
  17.     if (instructions.Length == 2)
  18.     {
  19.         var focalLength = int.Parse(instructions[1]);
  20.         var lens = (lensName, focalLength);
  21.         var lensIndex = box.FindIndex(l => l.Name == lensName);
  22.  
  23.         if (lensIndex > -1)
  24.         {
  25.             box[lensIndex] = lens;
  26.         }
  27.         else
  28.         {
  29.             box.Add(lens);
  30.         }
  31.     }
  32.     else
  33.     {
  34.         var lens = box.FirstOrDefault(l => l.Name == lensName);
  35.  
  36.         if (lens != default)
  37.         {
  38.             box.Remove(lens);
  39.         }
  40.     }
  41. }
  42.  
  43. var part2 = 0;
  44. for (var boxIndex = 0; boxIndex < boxes.Count; boxIndex++)
  45. {
  46.     part2 += boxes[boxIndex]
  47.         .Select((lens, lensIndex) => lens.FocalLength * (lensIndex + 1) * (boxIndex + 1))
  48.         .Sum();
  49. }
  50.  
  51. Console.WriteLine($"Part 2: {part2}");
  52. return;
  53.  
  54. static int Hash(string s)
  55. {
  56.     var i = 0;
  57.     foreach (var c in s)
  58.     {
  59.         i += c;
  60.         i *= 17;
  61.         i %= 256;
  62.     }
  63.  
  64.     return i;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement