My problem is as below:

I have a formula say b= a/b+c*d/d+e*c/d-f*h/g etc (can be any such huge formula)

and i need to rename the subformulas so that the formula size becomes smaller.Also it is better if positive/negative subformulas are grouped together.

i.e say i have a cut of of number of unique elements in a subfrmula to be 3, then i need to the above formula as:

b=p+q

p=a/b ( The number of elements can less than or equal to 3)

q=c*d/d+e*c/d ( the number of unique elements is only 3 i.e c,d,e)

r=-f*h/g

My current approach to solving the problem and where Iam stuck:

I have used 2 stacks called negative and positive stack which seperates the positive and negative subformulas as:

in thsi case Positive stack has :a/b , c*d/d

negative stack :f*h/g.

Also I have written a function that counts the unique elements in a subformula.

Now I need to be able to group the subformulas, where Iam facing the problem, can anyone direct me as to how to go about doing the same given the current implementation that I have done?

Thanks