AdventOfCode/2020/elixir/day18/day18part1.exs

32 lines
1,023 B
Elixir
Raw Normal View History

2020-12-18 08:27:16 +00:00
defmodule Day18Part1 do
def run do
File.stream!("input")
|> Stream.map(&parse_line/1)
|> Stream.map(&evaluate/1)
|> Enum.sum()
|> IO.puts()
end
def parse_line(line) do
line
|> String.graphemes()
|> Stream.reject(fn char -> char in [" ", "\n"] end)
|> Enum.map(fn
2020-12-18 09:13:33 +00:00
symbol when symbol in ["*", "+", "(", ")"] -> symbol
2020-12-18 08:27:16 +00:00
num -> String.to_integer(num)
end)
end
def evaluate(command), do: evaluate(command, nil, 0)
def evaluate([], nil, acc), do: acc
2020-12-18 09:13:33 +00:00
def evaluate(["*" | rest], nil, acc), do: evaluate(rest, "*", acc)
def evaluate(["+" | rest], nil, acc), do: evaluate(rest, "+", acc)
def evaluate(["(" | rest], op, acc), do: evaluate(rest) |> evaluate(op, acc)
def evaluate([")" | rest], nil, acc), do: [acc | rest]
def evaluate([num | rest], "*", acc), do: evaluate(rest, nil, acc * num)
def evaluate([num | rest], "+", acc), do: evaluate(rest, nil, acc + num)
2020-12-18 08:27:16 +00:00
def evaluate([num | rest], nil, 0), do: evaluate(rest, nil, num)
end
Day18Part1.run()