Hi, I’m trying to solve a problem where I want to generate all possible combinations from an array, with at most n elements. I was looking at this thread today: Most elegant way to generate all permutations? where this really nice solution was proposed by @OvermindDL1:
def permutations(), do: [] def permutations(list), do: for elem <- list, rest <- permutations(list--[elem]), do: [elem|rest]
So, I was trying to adapt this code to generate combinations with a fixed number of elements.
Example: Given the array
[1, 2, 3, 4] and a maximum size of 2, all possible combinations¹ would be:
[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3],
¹Just to be clear that: all possible combinations, in this case, means: combining every element with 2 more from the array until all elements have been combined.
PS.: I’m not completely comfortable with Elixir yet. So, forgive me if this is something too obvious to be asking here .