From 7a46852b2360b661375045d64de5db477678e4cc Mon Sep 17 00:00:00 2001 From: Adam Millerchip Date: Fri, 18 Dec 2020 18:13:33 +0900 Subject: [PATCH] Simplify --- day18/day18part1.exs | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/day18/day18part1.exs b/day18/day18part1.exs index 878a211..e8f0e1b 100644 --- a/day18/day18part1.exs +++ b/day18/day18part1.exs @@ -12,27 +12,19 @@ defmodule Day18Part1 do |> String.graphemes() |> Stream.reject(fn char -> char in [" ", "\n"] end) |> Enum.map(fn - "*" -> :multiply - "+" -> :add - "(" -> :start_group - ")" -> :end_group + symbol when symbol in ["*", "+", "(", ")"] -> symbol num -> String.to_integer(num) end) end def evaluate(command), do: evaluate(command, nil, 0) def evaluate([], nil, acc), do: acc - def evaluate([:multiply | rest], nil, acc), do: evaluate(rest, :multiply, acc) - def evaluate([:add | rest], nil, acc), do: evaluate(rest, :add, acc) - - def evaluate([:start_group | rest], op, acc) do - {remaining, group_result} = evaluate(rest, nil, 0) - evaluate([group_result | remaining], op, acc) - 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(["*" | 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) def evaluate([num | rest], nil, 0), do: evaluate(rest, nil, num) end