From 7dfc62354d8b37d9ad4e2ec5d946f28bd3d52e2b Mon Sep 17 00:00:00 2001 From: Caleb Webber Date: Fri, 13 Dec 2024 13:02:59 -0500 Subject: [PATCH] refactor day 13 to use modules --- elixir/livebook/2024/day13.livemd | 74 ++++++++++++++++++++----------- 1 file changed, 47 insertions(+), 27 deletions(-) diff --git a/elixir/livebook/2024/day13.livemd b/elixir/livebook/2024/day13.livemd index f8aeade..e7324f4 100644 --- a/elixir/livebook/2024/day13.livemd +++ b/elixir/livebook/2024/day13.livemd @@ -14,31 +14,51 @@ input = """ ``` ```elixir -for {a, b} <- (for line <- (input |> String.trim() |> String.split("\n")), reduce: {[], []} do - {vecs, matrices} = acc -> - case line do - "Button " <> rest -> - [[_, a, b]] = Regex.scan(~r/[AB]: X\+(\d+), Y\+(\d+)/, rest) - v = [a, b] |> Enum.map(&String.to_integer(&1)) - {[v | vecs], matrices} - "Prize: " <> rest -> - [[_, a, b]] = Regex.scan(~r/X=(\d+), Y=(\d+)/, rest) - v = [a, b] |> Enum.map(&String.to_integer(&1)) - a = Nx.tensor(vecs, type: :f64) |> Nx.transpose() - b = Nx.tensor(v |> Enum.map(&(&1+10000000000000)), type: :f64) - {[], [{a, b} | matrices]} - _ -> acc - end - end |> elem(1)), - c = Nx.LinAlg.invert(a) |> Nx.dot(b) |> Nx.round(), - b_prime = Nx.dot( - a, c - ) |> Nx.round() |> Nx.as_type(:f64), - c = Nx.as_type(c, :s64), - b == b_prime, - reduce: Nx.tensor(0, type: :s64) - do - acc2 -> - c |> Nx.dot(Nx.tensor([1, 3], type: :s64)) |> Nx.add(acc2) - end +defmodule ClawContraption do + def part1(input), do: parse(input, 0) |> solve() + def part2(input), do: parse(input, 10000000000000) |> solve() + + def parse(input, n) do + (for line <- (input |> String.trim() |> String.split("\n")), reduce: {[], []} do + {vecs, matrices} = acc -> + case line do + "Button " <> rest -> + [[_, a, b]] = Regex.scan(~r/[AB]: X\+(\d+), Y\+(\d+)/, rest) + v = [a, b] |> Enum.map(&String.to_integer(&1)) + {[v | vecs], matrices} + "Prize: " <> rest -> + [[_, a, b]] = Regex.scan(~r/X=(\d+), Y=(\d+)/, rest) + v = [a, b] |> Enum.map(&String.to_integer(&1)) + a = Nx.tensor(vecs, type: :f64) |> Nx.transpose() + b = Nx.tensor(v |> Enum.map(&(&1+n)), type: :f64) + {[], [{a, b} | matrices]} + _ -> acc + end + end |> elem(1)) + end + + def solve(systems) do + for {a, b} <- systems, + c = Nx.LinAlg.invert(a) |> Nx.dot(b) |> Nx.round(), + b_prime = Nx.dot( + a, c + ) |> Nx.round() |> Nx.as_type(:f64), + c = Nx.as_type(c, :s64), + b == b_prime, + reduce: Nx.tensor(0, type: :s64) + do + acc2 -> + c |> Nx.dot(Nx.tensor([1, 3], type: :s64)) |> Nx.add(acc2) + end + end +end + +``` + +```elixir +ClawContraption.part1(input) +``` + +```elixir +ClawContraption.part2(input) ```