1
$\begingroup$

There are $N$ optimization variables, $v_1,v_2,\cdots,v_N$. and $v_n\in{0,1,2,3,\cdots,K}$.

Let $N=10$ and $K=5$.

How can I generate all the possible combinations?

For example, the first combination is $[0\hspace{1mm} 0\hspace{1mm} 0\hspace{1mm} 0\hspace{1mm} 0\hspace{1mm} 0\hspace{1mm} 0\hspace{1mm} 0\hspace{1mm} 0\hspace{1mm} 0]$

The last combination is $[5\hspace{1mm} 5\hspace{1mm} 5\hspace{1mm} 5\hspace{1mm} 5\hspace{1mm} 5\hspace{1mm} 5\hspace{1mm} 5\hspace{1mm} 5\hspace{1mm} 5]$

${\bf EDIT}$: Then I need to filter out the tuples that do not give sum (of elements) exactly equal to 5.

Using

IntegerPartitions[5,{10},range[0,5]] is giving me some of the possible combinations, not all!

For example, its giving {1,1,1,1,1,0,0,0,0,0} as one of the candidate, but does not give {0,0,0,0,0,1,1,1,1,1} as another candidate.

$\endgroup$
  • $\begingroup$ Do you really want to generate them all? There 6^10 such tuples. I can't believe you have enough memory to store them. $\endgroup$ – m_goldberg Apr 30 at 10:51
  • 1
    $\begingroup$ try Tuples[Range[0,5],10] $\endgroup$ – J42161217 Apr 30 at 10:53
  • $\begingroup$ @J42161217, Thank you. Please see my edit. How can I now filter out the tuples that give sum more than 5 or any given number?. $\endgroup$ – dipak narayanan Apr 30 at 11:56
  • 2
    $\begingroup$ This can be done with IntegerPartitions more or less as in here. For example, try Table[IntegerPartitions[sum, {10}, Range[0, 5]], {sum, 6, 5 10}]. I think this almost has an answer in the linked question already. $\endgroup$ – Kiro Apr 30 at 12:13
  • 4
    $\begingroup$ Possible duplicate of How to generate the lists of $0 \leq m \leq X$ integer values so these values add up to $X$ as well as many others $\endgroup$ – Carl Woll Apr 30 at 18:57
2
$\begingroup$

try this

Select[Tuples[Range[0,5],10],Total@#<=5&]
$\endgroup$
1
$\begingroup$

Use Permutations together with IntegerPartitions:

With[{n = 10, k = 5},
  Join @@ Permutations /@ IntegerPartitions[k, {n}, Range[0, n]]]

{{5, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 5, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 5, 0, 0, 0, 0, 0, 0, 0}, ..., {0, 0, 0, 0, 0, 1, 1, 1, 1, 1}}

(2002 solutions in total).

There are $\binom{k+n-1}{k}$ solutions in total, which is a very small fraction of all $(k+1)^n$ tuples that you suggest to list and then filter (as in J42161217's solution). Better to do a direct construction like what I wrote above.

$\endgroup$

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