refactor day 13 to use modules
This commit is contained in:
parent
d2da4a5ce3
commit
7dfc62354d
1 changed files with 47 additions and 27 deletions
|
@ -14,7 +14,12 @@ input = """
|
||||||
```
|
```
|
||||||
|
|
||||||
```elixir
|
```elixir
|
||||||
for {a, b} <- (for line <- (input |> String.trim() |> String.split("\n")), reduce: {[], []} do
|
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 ->
|
{vecs, matrices} = acc ->
|
||||||
case line do
|
case line do
|
||||||
"Button " <> rest ->
|
"Button " <> rest ->
|
||||||
|
@ -25,11 +30,15 @@ for {a, b} <- (for line <- (input |> String.trim() |> String.split("\n")), reduc
|
||||||
[[_, a, b]] = Regex.scan(~r/X=(\d+), Y=(\d+)/, rest)
|
[[_, a, b]] = Regex.scan(~r/X=(\d+), Y=(\d+)/, rest)
|
||||||
v = [a, b] |> Enum.map(&String.to_integer(&1))
|
v = [a, b] |> Enum.map(&String.to_integer(&1))
|
||||||
a = Nx.tensor(vecs, type: :f64) |> Nx.transpose()
|
a = Nx.tensor(vecs, type: :f64) |> Nx.transpose()
|
||||||
b = Nx.tensor(v |> Enum.map(&(&1+10000000000000)), type: :f64)
|
b = Nx.tensor(v |> Enum.map(&(&1+n)), type: :f64)
|
||||||
{[], [{a, b} | matrices]}
|
{[], [{a, b} | matrices]}
|
||||||
_ -> acc
|
_ -> acc
|
||||||
end
|
end
|
||||||
end |> elem(1)),
|
end |> elem(1))
|
||||||
|
end
|
||||||
|
|
||||||
|
def solve(systems) do
|
||||||
|
for {a, b} <- systems,
|
||||||
c = Nx.LinAlg.invert(a) |> Nx.dot(b) |> Nx.round(),
|
c = Nx.LinAlg.invert(a) |> Nx.dot(b) |> Nx.round(),
|
||||||
b_prime = Nx.dot(
|
b_prime = Nx.dot(
|
||||||
a, c
|
a, c
|
||||||
|
@ -41,4 +50,15 @@ for {a, b} <- (for line <- (input |> String.trim() |> String.split("\n")), reduc
|
||||||
acc2 ->
|
acc2 ->
|
||||||
c |> Nx.dot(Nx.tensor([1, 3], type: :s64)) |> Nx.add(acc2)
|
c |> Nx.dot(Nx.tensor([1, 3], type: :s64)) |> Nx.add(acc2)
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
```elixir
|
||||||
|
ClawContraption.part1(input)
|
||||||
|
```
|
||||||
|
|
||||||
|
```elixir
|
||||||
|
ClawContraption.part2(input)
|
||||||
```
|
```
|
||||||
|
|
Loading…
Add table
Reference in a new issue