DEV Community

Anton
Anton

Posted on

Solving MakeArrayConsecutive2 on CodeSignal

The challenge:

Input: [6, 2, 3, 8]
Output: 3

To explain better the input and output relationship I need to sort the numbers first
[2,3,6,8]

You see that the numbers that are missing are 4,5, and 7.
How many numbers are missing? Exactly, 3. 3 is the answer.

Input: [0, 3]
Output: 2

Input: [5, 4, 6]
Output: 0

Input: [2]
Output: 0

The link to the challenge
An invite link to join CodeSignal

My first attempt:

defmodule MakeArrayConsecutive do
  # statues = [6, 2, 3, 8]
  # makeArrayConsecutive2(statues) = 3
  def makeArrayConsecutive2(statues) do
    statues
    |> Enum.sort()
    |> 
  end


  # What am I trying to do here?
  defp number_of_holes(sorted_list) do
    Enum.reduce(list, [],
      fn(x, []) ->
        [x]
      end
      fn(x, [head | tail] = whole_list) -> 
        if x - head =
      end
    )
  end
end

My second attempt, still not the full solution, but very close. I didn't account the case [0,3].

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

  defp check_singleton(xs) do
    case xs do
      [x] -> 0
      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}
        {number, difference} ->
          if x - number <= 1 do
            {x, difference}
          else
            {x, difference + (x - number - 1)}
          end
      end
    end)
  end
end

Latest comments (1)

Collapse
 
antonrich profile image
Anton • Edited

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