6
$\begingroup$

I'd like to generate all lists of length m containing all possible element combinations from a given list of length n with repetition. One way is to generate all tuples of the length m, then delete duplicates:

n = 5; m = 4;
Union[Sort /@ Tuples[Range[n], {m}]]

But already for $n=m=9$ it gives

General::nomem: The current computation was aborted because there was insufficient memory available to complete the computation.

And Subsets command gives subsets with every element present only once, so I don't see how it can be used here.

$\endgroup$
2
  • $\begingroup$ For example: n = 4; m = 3; and t = Permutations[Range[n], {m}] ? $\endgroup$
    – Syed
    Nov 19, 2021 at 15:08
  • $\begingroup$ @Syed no, Permutations uses every element once. $\endgroup$
    – Andrew
    Nov 19, 2021 at 18:01

1 Answer 1

6
$\begingroup$
mSubsets[n_, m_] := Sort[Join @@ 
  (Sort /@ IntegerPartitions[#, {m}, Range[n]] & /@ Range[m, n m])]

mSubsets[5, 3]

enter image description here

mSubsets[5, 4]

enter image description here

Length @ mSubsets[9, 9]
24310
$\endgroup$
1
  • 1
    $\begingroup$ Nice answer! Note, op (@Andrew), that to apply this to an arbitrary list, you can define mSubsets[n_Integer, m_Integer] := <as above> instead, and then define mSubsets[l_List, m_Integer] := Part[l, #] & /@ mSubsets[Length[l], m]. (Though there might be some speedup if you modify the original code cleverly instead, I'm not sure.) $\endgroup$
    – thorimur
    Nov 19, 2021 at 21:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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