Skip to content

Instantly share code, notes, and snippets.

@AntonFagerberg
Created May 21, 2015 08:21
Show Gist options
  • Save AntonFagerberg/611a1a2b9087141bdff3 to your computer and use it in GitHub Desktop.
Save AntonFagerberg/611a1a2b9087141bdff3 to your computer and use it in GitHub Desktop.
defmodule P5 do
def work(num, list, target, result \\ "")
def work(num, [], target, result) do
if num == target, do: IO.puts "#{result}#{num |> abs |> to_string}"
end
def work(num, [head | tail], target, result) do
work(head, tail, target - num, "#{result}#{abs(num)} + ")
work(-head, tail, target - num, "#{result}#{abs(num)} - ")
work(concat(num, head), tail, target, result)
end
def concat(a, b) do
zeroes = trunc(:math.log10(b)) + 1
result = abs(a) * trunc(:math.pow(10, zeroes)) + b
if abs(a) == a, do: result, else: -result
end
end
target = 100
[head | tail] = Enum.to_list(1..9)
P5.work(head, tail, target)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment