This commit is contained in:
Adam Millerchip 2020-12-18 18:13:33 +09:00
parent 1a687a0036
commit 7a46852b23

View file

@ -12,27 +12,19 @@ defmodule Day18Part1 do
|> String.graphemes() |> String.graphemes()
|> Stream.reject(fn char -> char in [" ", "\n"] end) |> Stream.reject(fn char -> char in [" ", "\n"] end)
|> Enum.map(fn |> Enum.map(fn
"*" -> :multiply symbol when symbol in ["*", "+", "(", ")"] -> symbol
"+" -> :add
"(" -> :start_group
")" -> :end_group
num -> String.to_integer(num) num -> String.to_integer(num)
end) end)
end end
def evaluate(command), do: evaluate(command, nil, 0) def evaluate(command), do: evaluate(command, nil, 0)
def evaluate([], nil, acc), do: acc def evaluate([], nil, acc), do: acc
def evaluate([:multiply | rest], nil, acc), do: evaluate(rest, :multiply, acc) def evaluate(["*" | rest], nil, acc), do: evaluate(rest, "*", acc)
def evaluate([:add | rest], nil, acc), do: evaluate(rest, :add, acc) def evaluate(["+" | rest], nil, acc), do: evaluate(rest, "+", acc)
def evaluate(["(" | rest], op, acc), do: evaluate(rest) |> evaluate(op, acc)
def evaluate([:start_group | rest], op, acc) do def evaluate([")" | rest], nil, acc), do: [acc | rest]
{remaining, group_result} = evaluate(rest, nil, 0) def evaluate([num | rest], "*", acc), do: evaluate(rest, nil, acc * num)
evaluate([group_result | remaining], op, acc) def evaluate([num | rest], "+", acc), do: evaluate(rest, nil, acc + num)
end
def evaluate([:end_group | rest], _op, acc), do: {rest, acc}
def evaluate([num | rest], :multiply, acc), do: evaluate(rest, nil, acc * num)
def evaluate([num | rest], :add, acc), do: evaluate(rest, nil, acc + num)
def evaluate([num | rest], nil, 0), do: evaluate(rest, nil, num) def evaluate([num | rest], nil, 0), do: evaluate(rest, nil, num)
end end