Created
May 17, 2019 17:00
-
-
Save Jwsonic/abc784adfa080dca561e1bc40d3ec977 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Digits do | |
@operators ["+", "-", "*"] | |
def calculate(num, target) do | |
# 1) Turn num into a list of characters | |
# 2) Build all possible equations | |
# 3) Filter out the ones that don't evaluate to the target | |
# 4) Clean up results for printing | |
num | |
|> String.graphemes() | |
|> build_equations() | |
|> Enum.filter(fn equation -> eval(equation) == target end) | |
|> Enum.join(", ") | |
end | |
# Base case where a single digit is left, we return that digit | |
defp build_equations([_] = last), do: last | |
# Case where there's 2+ digits left. | |
defp build_equations([first | rest]) do | |
# 1) Recursivley build out the rest of the possible equations | |
# 2) Append first and each operator to the front of the generated equations | |
rest | |
|> build_equations() | |
|> append_to_front(first) | |
end | |
defp append_to_front(equations, first) do | |
Stream.flat_map(equations, fn equation -> | |
Stream.map(@operators, fn op -> "#{first}#{op}#{equation}" end) | |
end) | |
end | |
# Cheat a bit and use built in eval | |
defp eval(equation) do | |
{result, _} = Code.eval_string(equation) | |
result | |
end | |
end | |
IO.puts("Input: num = \"123\", target = 6") | |
IO.puts("Output: [#{Digits.calculate("123", 6)}]") | |
IO.puts("Input: num = \"232\", target = 8") | |
IO.puts("Output: [#{Digits.calculate("232", 8)}]") | |
IO.puts("Input: num = \"00\", target = 0") | |
IO.puts("Output: [#{Digits.calculate("00", 0)}]") | |
IO.puts("Input: num = \"3456237490\", target = 9191") | |
IO.puts("Output: [#{Digits.calculate("3456237490", 9191)}]") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment