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()