Created
February 7, 2019 05:11
-
-
Save snewcomer/c61605d1ba497bc14d3c86a9f6e259fa to your computer and use it in GitHub Desktop.
closest kata
This file contains hidden or 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 Closest do | |
def closest(""), do: [{}, {}] | |
def closest(s) do | |
s | |
|> String.split | |
|> Enum.map(&String.to_integer/1) | |
|> Enum.with_index | |
|> Enum.map(&weight/1) | |
|> Enum.sort(&sort/2) | |
|> Enum.chunk(2, 1) | |
|> Enum.min_by(&min/1) | |
end | |
defp weight({x, i}), do: {x |> Integer.digits |> Enum.sum, i, x} | |
defp sort({d1, _, _}, {d2, _, _}), do: d1 <= d2 | |
defp min([{d1, _, _}, {d2, _, _}]), do: d2 - d1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment