I have a list $X=\{n_1,n_2,n_3,n_4, \dots, n_i\}$ with $n_i \in \mathbb{C}$, an integer $m \in \mathbb{N}$ and $S \in \mathbb{C}$. My question is how to find all solution to the equation
$$\sum_{j=1}^m x_j=S $$ in an efficient way with Mathematica?
An example:
X={1,1/2,0,-1/2,-1};
m=3;
S=1;
I want a function combinations[X,m,S]
which returns
combinations[X,m,S]
{{1,3,3},{3,1,3},{3,3,1},{1,2,4},{1,4,2},{2,1,4},{4,1,2},{2,4,1},{4,2,1},{1,1,5},{1,5,1},{5,1,1},{2,2,3},{2,3,2},{3,2,2}}
where each triple gives the index to X
.
For example, {1,3,3}
stands for
$$S=x_1+x_3+x_3=1+0+0=1.$$
The solution I have is very slow and takes a lot of memory: I perform m tensor-products of $X$, creating a $M=i \otimes i \otimes \dots \otimes i$ matrix (with dimension of $d(M)=i^m$, and sum each entry. Unfortunatly, the matrix M grows exponentially, and is unfeasible even for small $m$ below 20.
So let me two ask:
1) Do you know a more efficient solution for finding all solutions of the equation above?
2) Do you know a more efficient solution for finding all solutions of the equation above, for the special cases of $S=0$ and $S=1$?
IntegerPartitions[S, {m}, X]
and post-process (Permutations
)? $\endgroup$IntegerPartitions
before and couldnt get it work, i didnt know about the third argument. It works for rational numbers, that is already really cool, thanks! Could this be extended to complex values? (at least for question 2?) Thaanks!! $\endgroup$