Advertisement
mgla

Advent of Code - 2024 - Day 13

Dec 13th, 2024 (edited)
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1. var input = await File.ReadAllTextAsync("input.txt");
  2. var machineRecords = input.Split($"{Environment.NewLine}{Environment.NewLine}");
  3.  
  4. List<(int, int, int, int, int, int)> machines = [];
  5.  
  6. foreach (var record in machineRecords)
  7. {
  8.     var lines = record.Split(Environment.NewLine);
  9.  
  10.     var buttonA = lines[0][10..].Split(", ");
  11.     var ax = int.Parse(buttonA[0][2..]);
  12.     var ay = int.Parse(buttonA[1][2..]);
  13.  
  14.     var buttonB = lines[1][10..].Split(", ");
  15.     var bx = int.Parse(buttonB[0][2..]);
  16.     var by = int.Parse(buttonB[1][2..]);
  17.  
  18.     var prize = lines[2][7..].Split(", ");
  19.     var px = int.Parse(prize[0][2..]);
  20.     var py = int.Parse(prize[1][2..]);
  21.  
  22.     machines.Add((ax, ay, bx, by, px, py));
  23. }
  24.  
  25. for (var part = 1; part <= 2; part++)
  26. {
  27.     var correction = (part - 1) * 10000000000000L;
  28.     var result = 0L;
  29.  
  30.     foreach (var (ax, ay, bx, by, px0, py0) in machines)
  31.     {
  32.         var px = px0 + correction;
  33.         var py = py0 + correction;
  34.  
  35.         // We want to solve the following system of equations,
  36.         // where x is the number of presses for button A,
  37.         // and y is the number of presses for button B:
  38.         // ax*x + bx*y = px
  39.         // ay*x + by*y = py
  40.         // We solve it by applying Cramer's rule:
  41.         // x = (px*by - py*bx) / (ax*by - ay*bx)
  42.         // y = (ax*py - ay*px) / (ax*by - ay*bx)
  43.  
  44.         var d = ax * by - ay * bx;
  45.         var dx = px * by - py * bx;
  46.         var dy = ax * py - ay * px;
  47.  
  48.         if (dx % d != 0 || dy % d != 0)
  49.         {
  50.             // There is no integer solution, hence the prize is not reachable.
  51.             continue;
  52.         }
  53.  
  54.         var x = dx / d;
  55.         var y = dy / d;
  56.  
  57.         if (part == 1 && (x > 100 || y > 100))
  58.         {
  59.             continue;
  60.         }
  61.  
  62.         result += x * 3 + y;
  63.     }
  64.  
  65.     Console.WriteLine($"Part {part}: {result}");
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement