Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var input = await File.ReadAllTextAsync("input.txt");
- var machineRecords = input.Split($"{Environment.NewLine}{Environment.NewLine}");
- List<(int, int, int, int, int, int)> machines = [];
- foreach (var record in machineRecords)
- {
- var lines = record.Split(Environment.NewLine);
- var buttonA = lines[0][10..].Split(", ");
- var ax = int.Parse(buttonA[0][2..]);
- var ay = int.Parse(buttonA[1][2..]);
- var buttonB = lines[1][10..].Split(", ");
- var bx = int.Parse(buttonB[0][2..]);
- var by = int.Parse(buttonB[1][2..]);
- var prize = lines[2][7..].Split(", ");
- var px = int.Parse(prize[0][2..]);
- var py = int.Parse(prize[1][2..]);
- machines.Add((ax, ay, bx, by, px, py));
- }
- for (var part = 1; part <= 2; part++)
- {
- var correction = (part - 1) * 10000000000000L;
- var result = 0L;
- foreach (var (ax, ay, bx, by, px0, py0) in machines)
- {
- var px = px0 + correction;
- var py = py0 + correction;
- // We want to solve the following system of equations,
- // where x is the number of presses for button A,
- // and y is the number of presses for button B:
- // ax*x + bx*y = px
- // ay*x + by*y = py
- // We solve it by applying Cramer's rule:
- // x = (px*by - py*bx) / (ax*by - ay*bx)
- // y = (ax*py - ay*px) / (ax*by - ay*bx)
- var d = ax * by - ay * bx;
- var dx = px * by - py * bx;
- var dy = ax * py - ay * px;
- if (dx % d != 0 || dy % d != 0)
- {
- // There is no integer solution, hence the prize is not reachable.
- continue;
- }
- var x = dx / d;
- var y = dy / d;
- if (part == 1 && (x > 100 || y > 100))
- {
- continue;
- }
- result += x * 3 + y;
- }
- Console.WriteLine($"Part {part}: {result}");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement