Skip to content

Instantly share code, notes, and snippets.

@jbevain
Last active December 13, 2024 08:01
Show Gist options
  • Save jbevain/59bbe55c5da951d9bd9804716921e373 to your computer and use it in GitHub Desktop.
Save jbevain/59bbe55c5da951d9bd9804716921e373 to your computer and use it in GitHub Desktop.
List<Machine> machines = [];
foreach (var machine in input.Split("\n\n"))
{
var lines = machine.Split("\n");
var a = Split(lines[0]);
var b = Split(lines[1]);
var prize = Split(lines[2]);
static string[] Split(string s) => s.Split([' ', ',', ':', '+', '='], StringSplitOptions.RemoveEmptyEntries);
machines.Add(new Machine
{
A = (int.Parse(a[3]), int.Parse(a[5])),
B = (int.Parse(b[3]), int.Parse(b[5])),
Prize = (int.Parse(prize[2]) + 10000000000000L, int.Parse(prize[4]) + 10000000000000L)
});
}
long sum = 0;
foreach (var machine in machines)
{
if (ComputePresses(machine) is (long a, long b))
{
sum += Cost(a, b);
}
}
Console.WriteLine(sum);
static long Cost(long a, long b) => a * 3 + b;
static (long a, long b)? ComputePresses(in Machine machine)
{
return SolveEquations(machine.A.X, machine.B.X, machine.Prize.X, machine.A.Y, machine.B.Y, machine.Prize.Y) switch
{
(var a, var b) when double.IsInteger(a) && double.IsInteger(b) => ((long)a, (long)b),
_ => null
};
}
static (double a, double b)? SolveEquations(double x1, double x2, double x, double y1, double y2, double y)
{
return (x1 * y2 - x2 * y1) switch
{
0 => null,
var det => ((x * y2 - x2 * y) / det, (x1 * y - x * y1) / det)
};
}
struct Machine
{
public (int X, int Y) A;
public (int X, int Y) B;
public (long X, long Y) Prize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment