Sha256: 7ac6b22665df9c20846e7b46926262b17b7f7cf55dbd5f999b768aeb08e3b1c8

Contents?: true

Size: 960 Bytes

Versions: 327

Compression:

Stored size: 960 Bytes

Contents

defmodule Sublist do
  @doc """
  Returns whether the first list is a sublist or a superlist of the second list
  and if not whether it is equal or unequal to the second list.
  """
  def compare(a, b) do
    case { length(a), length(b) } do
      { la, lb } when la < lb ->
        if is_sublist(a, b, la, lb), do: :sublist, else: :unequal
      { la, lb } when la > lb ->
        if is_sublist(b, a, lb, la), do: :superlist, else: :unequal
      _ ->
        if a == b, do: :equal, else: :unequal
    end
  end

  defp is_sublist(_, _, len_a, len_b) when len_a > len_b, do: false
  defp is_sublist([], _, _, _), do: true  # empty is sublist of all non-empty
  defp is_sublist(a, b=[_|t], len_a, len_b) do
    if try_is_sublist(a, b) do
      true
    else
      is_sublist(a, t, len_a, len_b-1)
    end
  end

  defp try_is_sublist([], _), do: true
  defp try_is_sublist([x|at], [x|bt]), do: try_is_sublist(at, bt)
  defp try_is_sublist(_, _), do: false
end

Version data entries

327 entries across 327 versions & 1 rubygems

Version Path
trackler-2.2.1.109 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.108 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.107 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.106 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.105 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.104 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.103 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.102 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.101 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.100 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.99 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.98 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.97 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.96 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.95 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.94 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.93 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.92 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.91 tracks/elixir/exercises/sublist/example.exs
trackler-2.2.1.90 tracks/elixir/exercises/sublist/example.exs