1
0
Fork 0

reduce circuit instead of using ets

This commit is contained in:
Sloane Perrault 2022-09-21 09:19:53 -04:00
parent 7426db6489
commit be3a6da1ee

View file

@ -96,34 +96,27 @@ aoc 2015, 7 do
def circuit(), do: input_stream() |> Stream.map(&parse_instruction/1) |> Enum.into(%{}) def circuit(), do: input_stream() |> Stream.map(&parse_instruction/1) |> Enum.into(%{})
def p1 do def p1 do
:ets.new(:memo, [:set, :named_table])
circuit() circuit()
|> trace("a") |> trace("a")
|> then(&elem(&1, 1))
end end
def p2 do def p2 do
:ets.new(:memo, [:set, :named_table]) a = p1()
circuit() circuit()
|> Map.put("b", 956) |> Map.put("b", a)
|> trace("a") |> trace("a")
|> then(&elem(&1, 1))
end end
def trace(circuit, wire) when is_binary(wire) do def trace(circuit, wire) when is_binary(wire) do
case :ets.lookup(:memo, wire) do {circuit, traced} = trace(circuit, Map.get(circuit, wire))
[{^wire, value}] -> {Map.put(circuit, wire, traced), traced}
value
_ ->
value = trace(circuit, Map.get(circuit, wire))
:ets.insert(:memo, {wire, value})
value
end
end end
def trace(_circuit, signal) when is_integer(signal) do def trace(circuit, signal) when is_integer(signal) do
signal {circuit, signal}
end end
def trace(circuit, {:wire, wire}) do def trace(circuit, {:wire, wire}) do
@ -135,24 +128,35 @@ aoc 2015, 7 do
end end
def trace(circuit, {:or, lhs, rhs}) do def trace(circuit, {:or, lhs, rhs}) do
trace(circuit, lhs) ||| trace(circuit, rhs) {circuit, lhs} = trace(circuit, lhs)
{circuit, rhs} = trace(circuit, rhs)
{circuit, lhs ||| rhs}
end end
def trace(circuit, {:and, lhs, rhs}) do def trace(circuit, {:and, lhs, rhs}) do
trace(circuit, lhs) &&& trace(circuit, rhs) {circuit, lhs} = trace(circuit, lhs)
{circuit, rhs} = trace(circuit, rhs)
{circuit, lhs &&& rhs}
end end
def trace(circuit, {:lshift, lhs, rhs}) do def trace(circuit, {:lshift, lhs, rhs}) do
trace(circuit, lhs) <<< trace(circuit, rhs) {circuit, lhs} = trace(circuit, lhs)
{circuit, rhs} = trace(circuit, rhs)
{circuit, lhs <<< rhs}
end end
def trace(circuit, {:rshift, lhs, rhs}) do def trace(circuit, {:rshift, lhs, rhs}) do
trace(circuit, lhs) >>> trace(circuit, rhs) {circuit, lhs} = trace(circuit, lhs)
{circuit, rhs} = trace(circuit, rhs)
{circuit, lhs >>> rhs}
end end
def trace(circuit, {:not, arg}) do def trace(circuit, {:not, arg}) do
~~~trace(circuit, arg) {circuit, arg} = trace(circuit, arg)
{circuit, ~~~arg}
end end
def trace(_circuit, other), do: other
end end