Advertisement
mgla

Advent of Code 2024 - Day 5

Dec 5th, 2024 (edited)
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. var input = await File.ReadAllLinesAsync("input.txt");
  2.  
  3. var rules = new List<Rule>();
  4. var updates = new List<List<int>>();
  5.  
  6. var parsingRules = true;
  7.  
  8. foreach (var line in input)
  9. {
  10.     if (parsingRules)
  11.     {
  12.         if (string.IsNullOrWhiteSpace(line))
  13.         {
  14.             parsingRules = false;
  15.         }
  16.         else
  17.         {
  18.             var numbers = line.Split('|').Select(int.Parse).ToArray();
  19.             rules.Add(new Rule(numbers[0], numbers[1]));
  20.         }
  21.     }
  22.     else
  23.     {
  24.         updates.Add(line.Split(',').Select(int.Parse).ToList());
  25.     }
  26. }
  27.  
  28. var part1 = 0;
  29. var part2 = 0;
  30.  
  31. foreach (var update in updates)
  32. {
  33.     var isValid = true;
  34.     var matchingRules = new List<Rule>();
  35.  
  36.     foreach (var rule in rules)
  37.     {
  38.         var indexLeft = update.IndexOf(rule.Left);
  39.         var indexRight = update.IndexOf(rule.Right);
  40.  
  41.         if (indexLeft == -1 || indexRight == -1)
  42.         {
  43.             continue;
  44.         }
  45.  
  46.         matchingRules.Add(rule);
  47.  
  48.         if (indexLeft > indexRight)
  49.         {
  50.             isValid = false;
  51.         }
  52.     }
  53.  
  54.     if (isValid)
  55.     {
  56.         part1 += update[update.Count / 2];
  57.     }
  58.     else
  59.     {
  60.         update.Sort((a, b) =>
  61.         {
  62.             var rule = matchingRules.Find(r => r.Contains(a) && r.Contains(b));
  63.  
  64.             if (rule == default || rule.Left == a)
  65.             {
  66.                 return -1;
  67.             }
  68.  
  69.             return 1;
  70.         });
  71.  
  72.         part2 += update[update.Count / 2];
  73.     }
  74. }
  75.  
  76. Console.WriteLine($"Part 1: {part1}");
  77. Console.WriteLine($"Part 2: {part2}");
  78.  
  79. internal record Rule(int Left, int Right)
  80. {
  81.     public bool Contains(int i) => Left == i || Right == i;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement