Powered by AppSignal & Oban Pro

All combinations

livebooks/tips/all_combinations.livemd

All combinations

Combinations module

This module generates all combinations for extracting a specified number of elements from an list without duplication.

defmodule Combinations do
  def all(list) do
    1..length(list)
    |> Enum.reduce([], fn n, acc ->
      acc ++ all(list, n)
    end)
  end

  def all(_, 0), do: [[]]
  def all([], _), do: []
  def all(list, n) when length(list) == n, do: [list]

  def all([head | tail], n) do
    with_head = for combo <- all(tail, n - 1), do: [head | combo]
    without_head = all(tail, n)
    with_head ++ without_head
  end
end

Usage example

list = [1, 2, 3, 4]
Combinations.all(list, 2)
Combinations.all(list, 3)
Combinations.all(list)