Skip to content

Instantly share code, notes, and snippets.

@ktec
Last active April 21, 2017 07:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktec/9f27e685697f3fceebe53327238b3378 to your computer and use it in GitHub Desktop.
Save ktec/9f27e685697f3fceebe53327238b3378 to your computer and use it in GitHub Desktop.
defmodule PyramidCalculator do
@doc """
iex> PyramidCalculator.pyramid_prices_percents([1, 2, 3], 10)
[10.0, 33.33333333333333, 56.666666666666664]
iex> PyramidCalculator.pyramid_prices_percents([1, 2, 3], 40)
[40.0, 33.333333333333336, 26.666666666666668]
iex> PyramidCalculator.pyramid_prices_percents([1, 3, 7, 22], 5)
[5.0, 10.517241379310345, 21.551724137931036, 62.93103448275862]
"""
def pyramid_prices_percents(prices, initial_percent) do
total_pyramid_percent = 100 - Enum.count(prices) * initial_percent
total_distance = total_distance(prices)
calc = fn (price) ->
initial_percent + (price / total_distance) * total_pyramid_percent
end
abs_prices(prices) |> Enum.map(calc)
end
defp total_distance(prices), do: prices |> abs_prices |> Enum.sum
defp abs_prices([h|_] = xs), do: xs |> Enum.map(&(abs(&1 - h)))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment