Skip to content

Instantly share code, notes, and snippets.

@snewcomer
Created February 7, 2019 05:11
Show Gist options
  • Save snewcomer/c61605d1ba497bc14d3c86a9f6e259fa to your computer and use it in GitHub Desktop.
Save snewcomer/c61605d1ba497bc14d3c86a9f6e259fa to your computer and use it in GitHub Desktop.
closest kata
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