Suppose I have a list
lis={a,b,c,d,e,f};
Is there a way to get all the combination of 3 elements (without order) from it? I try to use
Flatten[Permutations /@ Subsets[lis, {3}], 1]
But it not contains the repeated elements, that is I want the elements such as {a,a,a}
be included also.
Answer
Using Subsets
you can avoid deleting many duplicates
Multisets[s_List, n_Integer] := With[{u = Range[0, n - 1]},
s[[# - u]] & /@ Subsets[Range[Length[s] + n - 1], {n}]]
Multisets[{a, b, c, d, e}, 3]
This vectorized version is probably faster:
Multisets[s_List, n_Integer] := Partition[s[[Flatten[Transpose[Subsets[
Range[Length[s] + n - 1], {n}]] - Range[0, n - 1], {2, 1}]]], n]
Comments
Post a Comment