# All possible combinations of ways to write an equation

I want to define a function in Mathematica where I get all combinations of an expression, e.g., input:

{q,p1,p2}


Output:

{q + p1 + p2, q + p1 - p2, q - p1 + p2, -q + p1 + p2, -q - p1 + p2, -q + p1 - p2, -q - p1 - p2}


I am only interested in Plus/Minus.

I really need your help guys.

Tuples + Dot:

Tuples[{1, -1}, 3].{q, p1, p2}


{p1 + p2 + q, p1 - p2 + q, -p1 + p2 + q, -p1 - p2 + q, p1 + p2 - q, p1 - p2 - q, -p1 + p2 - q, -p1 - p2 - q}

For arbitrary number of variables:

ClearAll[f]
f[n_] := Tuples[{1, -1}, n].Array[Subscript[q, #] &, n]

f[3] // TeXForm


$$\scriptsize\left\{q_1+q_2+q_3,q_1+q_2-q_3,q_1-q_2+q_3,q_1-q_2-q_3,-q_1+q_2+q_3,-q_1+q_2-q_3,-q_1-q_2+q_3,-q_1-q_2-q_3\right\}$$

Also

Flatten @ Outer[{q, p1, p2}.{##} &, {1, -1}, {1, -1}, {1, -1}]


{p1 + p2 + q, p1 - p2 + q, -p1 + p2 + q, -p1 - p2 + q, p1 + p2 - q, p1 - p2 - q, -p1 + p2 - q, -p1 - p2 - q}

• Thanks for your answer. Can you give me an example of how to extend it for q,p1,p2,..pn
– NeAr
Feb 19, 2020 at 15:20
• @user69814, i added a generalization for n variables.
– kglr
Feb 19, 2020 at 15:33
• You are the best. Thanks alot :)
– NeAr
Feb 19, 2020 at 15:40
{q, p1, p2}*# & /@ Tuples[{+1, -1}, 3]


{{q, p1, p2}, {q, p1, -p2}, {q, -p1, p2}, {q, -p1, -p2}, {-q, p1, p2}, {-q, p1, -p2}, {-q, -p1, p2}, {-q, -p1, -p2}}