Created
August 13, 2015 01:20
-
-
Save 5thWall/5a7f568a8b54f4f6c1cb to your computer and use it in GitHub Desktop.
Range Extractor from Codewars
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
# http://www.codewars.com/kata/51ba717bb08c1cd60f00002f | |
defmodule RangeExtractor do | |
def solution([head | tail]) do | |
_solution(tail, [head], []) | |
end | |
defp _solution([], [], acc) do | |
acc | |
|> Enum.reverse | |
|> Enum.join(", ") | |
end | |
defp _solution([], range, acc) when length(range) >= 3 do | |
_solution([], [], [format_range(range) | acc]) | |
end | |
defp _solution([], range, acc) do | |
_solution([], [], range ++ acc) | |
end | |
defp _solution([head | tail], range, acc) when (hd(range) + 1) == head do | |
_solution(tail, [head | range], acc) | |
end | |
defp _solution([head | tail], range, acc) when length(range) >= 3 do | |
_solution(tail, [head], [format_range(range) | acc]) | |
end | |
defp _solution([head | tail], range, acc) do | |
_solution(tail, [head], range ++ acc) | |
end | |
defp format_range(range) do | |
last = hd(range) | |
first = range |> Enum.reverse |> hd | |
"#{first}-#{last}" | |
end | |
end | |
list = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] | |
list | |
|> RangeExtractor.solution | |
|> IO.puts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment