# Way to generate all multisets

I have a set $\left\{\{1,2\}, \{3,4\}, \{5,6\}, \{7,8\}\right\}$ (for example) and want to generate all sets of $n$ elements with repetition but without counting the same multiset twice. So I want my generated list to contain: (say $n$ = 3)

$\{\{1,2\}, \{1,2\}, \{3,4\}\}$ and $\{\{1,2\}, \{3,4\}, \{5,6\}\}$ but I don't also want $\{\{1,2\}, \{3,4\}, \{1,2\}\}$ as that should be the same as the first set. (Well, I want this set but flattened, like $\{1,2,1,2,3,4\}$, etc, but I kept the brackets in to be more illustrative.)

Example: I have $\{\{1,2\}, \{3,4\}, \{5,6\}\}$ and $n =2$, then I want to generate $\{\{1,2,1,2\}, \{1,2,3,4\},\{1,2,5,6\}, \{3,4,3,4\}, \{3,4,5,6\}, \{5,6,5,5\}\}$

The only way I can think of is making a table then write some long loop thing to remove the repetitions and I'm sure there's a much more efficient way to do this. Probably invoke constant array somehow but I really have no idea how to implement it. Thanks for the help!

• Union[Sort /@ Tuples[Partition[Range, 2], 3]]? – J. M.'s torpor Oct 20 '15 at 1:52
• Flatten /@ Tuples[{{1, 2}, {3, 4}, {5, 6}, {7, 8}}, {2}] ? – Prashanth Oct 20 '15 at 2:44
• @J.M. This works nicely, thanks! – user46348 Oct 20 '15 at 18:50
• @Prashanth This is close, but there is repetion. Thanks for the suggestion though! – user46348 Oct 20 '15 at 18:50

data = Partition[Range, 2];


Read the documentation for Tuples as recommended by J.M and Prashanth.

Tuples[data, 3]


Generates a list of all possible 3-tuples of elements from list.

Because order is nor relevant you will have duplicates. So you need to sort and remove the permutations.

multisets[data_, n_] := Union[Sort /@ Tuples[data, n]]


Now use with n -> 3

multisets[data, 3]

{{{1, 2}, {1, 2}, {1, 2}}, {{1, 2}, {1, 2}, {3, 4}}, {{1, 2}, {1,
2}, {5, 6}}, {{1, 2}, {1, 2}, {7, 8}}, {{1, 2}, {3, 4}, {3,
4}}, {{1, 2}, {3, 4}, {5, 6}}, {{1, 2}, {3, 4}, {7, 8}}, {{1,
2}, {5, 6}, {5, 6}}, {{1, 2}, {5, 6}, {7, 8}}, {{1, 2}, {7, 8}, {7,
8}}, {{3, 4}, {3, 4}, {3, 4}}, {{3, 4}, {3, 4}, {5, 6}}, {{3,
4}, {3, 4}, {7, 8}}, {{3, 4}, {5, 6}, {5, 6}}, {{3, 4}, {5, 6}, {7,
8}}, {{3, 4}, {7, 8}, {7, 8}}, {{5, 6}, {5, 6}, {5, 6}}, {{5,
6}, {5, 6}, {7, 8}}, {{5, 6}, {7, 8}, {7, 8}}, {{7, 8}, {7, 8}, {7,
8}}}

• Thanks for this! Very helpful. There is a small error though which I can't edit because it's not 6 characters? But it should be Tuples[data,n]]. – user46348 Oct 20 '15 at 18:43