Fast algorithm for finding all solutions of simple equation involving only addition of terms from list
For rational $n_i$ and $S$, you can use IntegerPartitions
:
X = {1, 1/2, 0, -1/2, -1};
m = 3;
S = 1;
posIndex=PositionIndex[X];
Flatten /@ Map[posIndex, Join @@ (Permutations /@ IntegerPartitions[S, {m}, X]), {-1}]
{{5, 1, 1}, {1, 5, 1}, {1, 1, 5}, {4, 2, 1}, {4, 1, 2}, {2, 4, 1}, {2,1, 4}, {1, 4, 2}, {1, 2, 4}, {3, 3, 1}, {3, 1, 3}, {1, 3, 3}, {3, 2, 2}, {2, 3, 2}, {2, 2, 3}}
Could use Solve
.
The example in question:
xvals = {1, 1/2, 0, -1/2, -1};
m = 3;
ss = 1;
Set up the equations and inequalities that need to be enforced.
vars = Array[n, Length[xvals]];
constraints =
Flatten[{Total[vars] - m == 0, vars.xvals - ss == 0,
Thread[vars >= 0]}];
Solve[constraints, vars, Integers]
(* Out[221]= {{n[1] -> 0, n[2] -> 2, n[3] -> 1, n[4] -> 0,
n[5] -> 0}, {n[1] -> 1, n[2] -> 0, n[3] -> 2, n[4] -> 0,
n[5] -> 0}, {n[1] -> 1, n[2] -> 1, n[3] -> 0, n[4] -> 1,
n[5] -> 0}, {n[1] -> 2, n[2] -> 0, n[3] -> 0, n[4] -> 0, n[5] -> 1}} *)