add 2024 day 13
This commit is contained in:
parent
04ce5b915f
commit
d2da4a5ce3
1 changed files with 44 additions and 0 deletions
44
elixir/livebook/2024/day13.livemd
Normal file
44
elixir/livebook/2024/day13.livemd
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
# AOC 2024 Day 13
|
||||||
|
|
||||||
|
```elixir
|
||||||
|
Mix.install([
|
||||||
|
{:nx, "0.9.2"}
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
## Section
|
||||||
|
|
||||||
|
```elixir
|
||||||
|
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
|
||||||
|
```
|
Loading…
Add table
Reference in a new issue