refactor day 13 to use modules

This commit is contained in:
Caleb Webber 2024-12-13 13:02:59 -05:00
parent d2da4a5ce3
commit 7dfc62354d

View file

@ -14,31 +14,51 @@ input = """
``` ```
```elixir ```elixir
for {a, b} <- (for line <- (input |> String.trim() |> String.split("\n")), reduce: {[], []} do defmodule ClawContraption do
{vecs, matrices} = acc -> def part1(input), do: parse(input, 0) |> solve()
case line do def part2(input), do: parse(input, 10000000000000) |> solve()
"Button " <> rest ->
[[_, a, b]] = Regex.scan(~r/[AB]: X\+(\d+), Y\+(\d+)/, rest) def parse(input, n) do
v = [a, b] |> Enum.map(&String.to_integer(&1)) (for line <- (input |> String.trim() |> String.split("\n")), reduce: {[], []} do
{[v | vecs], matrices} {vecs, matrices} = acc ->
"Prize: " <> rest -> case line do
[[_, a, b]] = Regex.scan(~r/X=(\d+), Y=(\d+)/, rest) "Button " <> rest ->
v = [a, b] |> Enum.map(&String.to_integer(&1)) [[_, a, b]] = Regex.scan(~r/[AB]: X\+(\d+), Y\+(\d+)/, rest)
a = Nx.tensor(vecs, type: :f64) |> Nx.transpose() v = [a, b] |> Enum.map(&String.to_integer(&1))
b = Nx.tensor(v |> Enum.map(&(&1+10000000000000)), type: :f64) {[v | vecs], matrices}
{[], [{a, b} | matrices]} "Prize: " <> rest ->
_ -> acc [[_, a, b]] = Regex.scan(~r/X=(\d+), Y=(\d+)/, rest)
end v = [a, b] |> Enum.map(&String.to_integer(&1))
end |> elem(1)), a = Nx.tensor(vecs, type: :f64) |> Nx.transpose()
c = Nx.LinAlg.invert(a) |> Nx.dot(b) |> Nx.round(), b = Nx.tensor(v |> Enum.map(&(&1+n)), type: :f64)
b_prime = Nx.dot( {[], [{a, b} | matrices]}
a, c _ -> acc
) |> Nx.round() |> Nx.as_type(:f64), end
c = Nx.as_type(c, :s64), end |> elem(1))
b == b_prime, end
reduce: Nx.tensor(0, type: :s64)
do def solve(systems) do
acc2 -> for {a, b} <- systems,
c |> Nx.dot(Nx.tensor([1, 3], type: :s64)) |> Nx.add(acc2) c = Nx.LinAlg.invert(a) |> Nx.dot(b) |> Nx.round(),
end 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)
``` ```