Goba
Goba

Reputation: 57

Generate variations with repetitions Erlang

I've found a way to generate the combinations of a list, but here order doesn't matter, but I need to generate variations where order matters.

Combination:

comb_rep(0,_) ->
    [[]];
comb_rep(_,[]) ->
    [];
comb_rep(N,[H|T]=S) ->
    [[H|L] || L <- comb_rep(N-1,S)]++comb_rep(N,T).

Output of this:

comb_rep(2,[1,2,3]).
[[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]

Desired output:

comb_rep(2,[1,2,3]).
[[1,1],[1,2],[1,3],[2,2],[2,3],[3,1],[3,2],[3,3]]

Upvotes: 0

Views: 206

Answers (1)

Brujo Benavides
Brujo Benavides

Reputation: 1958

Following what’s explained in the comments, this will be my initial approach:

cr(0, _) ->
    [];
cr(1, L) ->
    [ [H] || H <- L ];
cr(N, L) ->
    [ [H | T] || H <- L, T <- cr(N - 1, L -- [H]) ].

Permutations of length 0 is an edge case. I would even consider the removal of that clause so that the function fails if invoked as such.

Permutations of length 1 means just means each element in its own list.

Then, for the recursive case, if you already have the permutations of the list without the current element (cr(N - 1, L -- [H])) you can just add that element to the head of each list and you just need to do that for each element in the original list (H <- L).

Hope this helps.

Upvotes: 3

Related Questions