Replace sum x+y+z in expressions like 2x+3y+z
You can use PolynomialReduce
for this:
reduce[e_, p_Symbol->r_, v_List] := Module[{min},
min = First @ Ordering[Coefficient[e,#]&/@v];
Replace[
PolynomialReduce[e, r, v[[min]]],
{{n_}, s_} :> s + n p
]
]
Then:
reduce[3x + 2y + 5z, p -> x + y + z, {x, y, z}]
reduce[3x + 2y, p -> x + y + z, {x, y, z}]
2 p + x + 3 z
3 x + 2 y
You can build another kind of rule
rule = a_. x + b_. y + c_. z :> (((a - min) x + (b - min) y +
(c - min) z + min p) /. {min -> Min[a, b, c]})
Then
(5x+2y+3z /.rule) == 2p+3x+z
(3x+2y /.rule) == 3x + 2y
Clear["Global`*"]
repl[expr_, vars : _List : {z, y, x}, p : _Symbol : p] :=
SortBy[expr /.
(Solve[Total[vars] == p, #][[1]] & /@ vars) // Simplify,
LeafCount][[1]]
5 x + 2 y + 3 z // repl
(* 2 p + 3 x + z *)
3 x + 2 y // repl
(* 3 x + 2 y *)