Related threads replacing-a-sum-of-expressions and Replace a sum of squared variables by a new squared variable
Given the identity $x+y+z=p$ I'd like to simplify the generic expression
$$kx+ly+mz$$
where $k$, $l$, $m$ are positive integer coefficients, but ultimately this shouldn't matter.
The naive ansatz would be to use the rule
HoldPattern[Plus[x,y,z]]->p
This works fine when $k=1$, $l=1$, and $m=1$ but fails in all other cases. Now the accepted answer in the first linked post, states that you need to define all the rules manually. But this gives this massive object, which leads to $2^c$ possibilities, where $c$ is the number of coefficients.
HoldPattern[Plus[x, y, z]] -> p,
HoldPattern[Plus[Times[a_?IntegerQ, x], y, z]] :>
Plus[Times[a - 1, x], y, z, p],
HoldPattern[Plus[Times[a_?IntegerQ, y], x, z]] :>
Plus[Times[a - 1, y], x, z, p],
HoldPattern[Plus[Times[a_?IntegerQ, z], x, y]] :>
Plus[Times[a - 1, z], x, y, p],
HoldPattern[Plus[Times[a_?IntegerQ, x], Times[b_?IntegerQ, y], z]] :>
Plus[Times[a - Min[a, b], x], Times[b - Min[a, b], y], z, p],
HoldPattern[Plus[Times[a_?IntegerQ, x], Times[b_?IntegerQ, z], y]] :>
Plus[Times[a - Min[a, b], x], Times[b - Min[a, b], z], y, p],
HoldPattern[Plus[Times[a_?IntegerQ, y], Times[b_?IntegerQ, z], x]] :>
Plus[Times[a - Min[a, b], y], Times[b - Min[a, b], z], x, p],
HoldPattern[
Plus[Times[a_?IntegerQ, x], Times[b_?IntegerQ, y],
Times[c_?IntegerQ, z]]] :>
Plus[Times[a - Min[a, b, c], x], Times[b - Min[a, b, c], y],
Times[c - Min[a, b, c], z], Times[Min[a, b, c], p]]
}
It should be obvious, that
- There is a lot of repetition in this code and as a consequence
- This generalizes very badly, due to the exponential scaling of the possibilities
Example expected results:
- $5x+2y+3z=3x+z+2p$
- $3x+2y$ should remained unchanged (optionally)
- $x+2y+z=p+y$
What is the general way to apply the above identity to any expression?
Additional requirement (edited): $p$ should be able to be a more complicated expression, not necessarily atomic.
Eliminate[{ss == 5 x + 2 y + 3 z, p == x + y + z}, y]? – kglr Oct 09 '20 at 15:34z -> p-x-y? – Eric Towers Oct 10 '20 at 02:26z– infinitezero Oct 10 '20 at 14:10