re: Solving MakeArrayConsecutive2 on CodeSignal VIEW POST

FULL DISCUSSION
 

And final solution, which as admittedly very verbose.

defmodule MakeArrayConsecutive do
  # statues = [6, 2, 3, 8]
  # makeArrayConsecutive2(statues) = 3
  def makeArrayConsecutive2(statues) do
    case check_singleton_or_double(statues) do
      0 ->
        0
      [x, y] -> y - x - 1
      list ->
        list
        |> Enum.sort()
        |> number_of_holes()
        |> return_difference()
    end
  end

  # I rename the function and added a second case when the list has two items.
  defp check_singleton_or_double(xs) do
    case xs do
      [x] -> 0
      [x, y] -> Enum.sort([x, y])
      list -> list
    end
  end

  defp return_difference({x, y}) do
    y
  end

  defp number_of_holes(sorted_list) do
    Enum.reduce(sorted_list, {0, 0}, fn(x, acc) ->
      case acc do
        {0,0} ->
          {x, 0}
          |> IO.inspect()
        {number, difference} ->
          if x - number <= 1 do
            {x, difference}
            |> IO.inspect()
          else
            {x, difference + (x - number - 1)}
            |> IO.inspect()
          end
      end
    end)
  end
end
code of conduct - report abuse