I have an equation : 100 + (y * 5) = 200
I have to find the value of y = (200 -100)/5, but the main thing is operators sign may changes ( for eg: 100 * (y -5) = 200 ), So How to write a program such that if the equation is passed, it solve and gives the value of x, irrespective of whatever operators are used.
Any help is appreciated.
I have tried below in node js and have to solve equation :
var fs = require('fs');
fs.readFile('equation.json',
// callback function that is called when reading file is done
function(err, data) {
// json data
var jsonData = data;
// parse json
var jsonParsed = JSON.parse(jsonData);
//operators array
var operators = {
"add":"+",
"subtract":"-",
"multiply":"*",
"divide":"/",
"equal":"="
};
var eq,op1,op2,equation;
for(opt in operators){
if(jsonParsed.op == opt){
eq = operators.equal;
}
//looking for first operator
if(jsonParsed.lhs.op == opt){
if(opt=="add"){
op1 = operators.add;
}
else if(opt=="subtract"){
op1 = operators.subtract;
}
else if(opt=="multiply"){
op1 = operators.multiply;
}
else if(opt=="divide"){
op1 = operators.divide;
}
}
//looking for second operator
if(jsonParsed.lhs.rhs.op == opt){
if(opt=="add"){
op2 = operators.add;
}
else if(opt=="subtract"){
op2 = operators.subtract;
}
else if(opt=="multiply"){
op2 = operators.multiply;
}
else if(opt=="divide"){
op2 = operators.divide;
}
}
}
//console.log(eq);
//console.log(op1);
//console.log(op2)
//parsing expression
equation = jsonParsed.lhs.lhs + op1 +"(" + jsonParsed.lhs.rhs.lhs + op2 + jsonParsed.lhs.rhs.rhs + ")" + eq + jsonParsed.rhs;
console.log(equation);
});
JSON
{
"op": "equal",
"lhs": {
"op": "add",
"lhs": 1,
"rhs": {
"op": "multiply",
"lhs": "x",
"rhs": 10
}
},
"rhs": 21
}