0

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.

user64494
  • 26,149
  • 4
  • 27
  • 56
MGK
  • 565
  • 3
  • 9

2 Answers2

1

try this

Select[Tuples[Range[0,5],10],Total@#<=5&]
ZaMoC
  • 6,697
  • 11
  • 31
0

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.

Roman
  • 47,322
  • 2
  • 55
  • 121