prasanth sadhana - 6 months ago 15
Javascript Question

# How to get the sum of Alike Terms in a mathematical equation string using Distributive Law

I have creating program for solving the equation.In my first step separate the alphabets and adding same alphabets values.
In my equation like:-

`10x+9k-12k-3a-8a=100`
alphabets present anything between
`A-Z`
.In my question is how to separate the alphabets.And adding the same alphabets numeric value .i need a answer like from the equation.
`separate the x(10),k(9,-12),a(3,-8)`

``````    `value of x=10;
value of k=-3;
value of a=-11;`
``````

I wrote a parser for you, you can tweak it as you like

``````var str = '10x+9k-12k-3a-8a=100';
var reg = /([\-+])?\s*(\d+)?([a-z])/g;
var store = {};

function evaluateExp(){

var res = reg.exec(str);
while(res){

if(!store[res[3]]){
store[res[3]] = [];
}

store[res[3]].push({
sign: res[1] || '+',
multiplier: (typeof res[2] != 'undefined') ? parseInt(res[2], 10) : 1
});
res = reg.exec(str);
}

Object.keys(store).forEach(function(key){

let val = 0;

store[key].forEach(function(occ){
if(occ.sign == '+')
val += occ.multiplier;
else
val -= occ.multiplier;
});

\$('ul#results').append('<li>value of '+ key +"="+ val + ';</li>');
});

}

``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>