From 1511d22b8c0762f175a0261ac2096d9214576044 Mon Sep 17 00:00:00 2001 From: Dustin Swan Date: Sat, 14 Dec 2024 21:32:29 -0700 Subject: [PATCH] Day 13. Had to look up how to solve equations, found cramer --- day13/main.exs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 day13/main.exs diff --git a/day13/main.exs b/day13/main.exs new file mode 100644 index 0000000..86ecfaf --- /dev/null +++ b/day13/main.exs @@ -0,0 +1,57 @@ +defmodule Day13 do + def run do + machines = + File.read!("data.txt") + |> String.trim() + |> String.split("\n\n") + |> Enum.map(&parse_machine/1) + + # part1 + machines |> score |> dbg + + # part 2 + machines + |> Enum.map(fn [a, b, c, d, e, f] -> + [a, b, c, d, e + 10_000_000_000_000, f + 10_000_000_000_000] + end) + |> score + |> dbg + end + + defp score(machines) do + Enum.map(machines, &solve/1) + |> Enum.reject(&is_nil/1) + |> Enum.sum() + end + + defp solve([ax, ay, bx, by, px, py]) do + # X: 94A + 22B = 8400 + # a x + b y = e + # Y: 22A + 67B = 5400 + # c x + d y = f + # + # determinant = ad - bc + # x = (e*d - b*f)/determinant + # y = (a*f - e*c)/determinant + + determinant = ax * by - bx * ay + + if determinant == 0 do + nil + else + x = (px * by - bx * py) / determinant + y = (ax * py - px * ay) / determinant + + if trunc(x) == x and trunc(y) == y, do: x * 3 + y, else: nil + end + end + + defp parse_machine(m) do + ~r/Button A: X\+(\d+).*Y\+(\d+)\nButton B: X\+(\d+).*Y\+(\d+)\nPrize: X=(\d+), Y=(\d+).*/ + |> Regex.run(m) + |> tl + |> Enum.map(&String.to_integer/1) + end +end + +Day13.run()