defmodule Main do

  @doc """
  count median

  ## Examples

      iex> CountMedian.count_median([[1, 2], [2, 3]], 2)
      3
      iex> CountMedian.count_median([[100, 100], [10, 10000], [1, 1000000000]], 3)
      9991

  """
  def count_median(list_of_lists, n) do
    list_of_a =
      list_of_lists
      |> Enum.map(fn [a, _] -> a end)

    list_of_b =
      list_of_lists
      |> Enum.map(fn [_, b] -> b end)

      do_count_median(list_of_a, list_of_b, n)
  end

  defp do_count_median(list_of_a, list_of_b, n) when rem(n, 2) == 1 do
    i = div(n, 2)
    Enum.at(list_of_b, i) - Enum.at(list_of_a, i) + 1
  end

  defp do_count_median(list_of_a, list_of_b, _n) do
    div(Enum.at(list_of_b, 0) + Enum.at(list_of_b, -1), 2) + 1
  end

  def permutation(_, 0), do: [[]]

  def permutation(list, n) do
    for x <- list, rest <- permutation(list -- [x], n - 1), do: [x | rest]
  end
end
