3
$\begingroup$

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!

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

1 Answer 1

3
$\begingroup$

Your data:

data = Partition[Range[8], 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}}}
$\endgroup$
1
  • $\begingroup$ 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]]. $\endgroup$
    – user46348
    Commented Oct 20, 2015 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.