Algorithm to solve linear equation in one variable
0
/
298

<script> /** * @param {string} equation * @return {string} */ function solveEquation(equation) { var arr = equation.split("="); var lhs = arr[0], rhs = arr[1]; var lhsxcoeff, lhsconstant, rhsxcoeff, rhsconstant; // if LHS equals RHS if (lhs === rhs) return "Infinite solutions"; // parse and extract lhs x coefficient and constant [lhsxcoeff, lhsconstant] = parse(lhs); // parse and extract rhs x coefficient and constant [rhsxcoeff, rhsconstant] = parse(rhs); // compute the final x coefficient by substracting RHS x coeff. from LHS x coeff. var finalXcoeff = lhsxcoeff - rhsxcoeff; // if the RHS and LHS coeffcients and constants match respectively if (lhsxcoeff === rhsxcoeff && lhsconstant === rhsconstant) return "Infinite solutions"; // if there is no final x coefficient left say for e.g. in equations like x = x + 2; if (finalXcoeff === 0) return "No solution"; // final case compute the value of x if (finalXcoeff >= 1 || finalXcoeff < 0) { return 'x=' + ((rhsconstant - lhsconstant) / finalXcoeff); } }; // parse equation (LHS and RHS) using regex function parse(expression) { var arr = expression.match(/-?(\d*x|\d+)/g); var finalXCoefficient = 0; var constantSum = 0; for (var i = 0; i < arr.length; i++) { if (arr[i].match(/x/g)) { var xcoefficient = arr[i].substring(0, arr[i].length - 1); if (xcoefficient === '-') xcoefficient = -1; if (xcoefficient === '') xcoefficient = 1; finalXCoefficient += parseInt(xcoefficient); } else constantSum += parseInt(arr[i]); } return [finalXCoefficient, constantSum]; } document.write(solveEquation("x+5-3+x=6+x-2")+'<br/>'); document.write(solveEquation("x=x")+'<br/>'); document.write(solveEquation("2x=x")+'<br/>'); document.write(solveEquation("2x+3x-6x=x+2")+'<br/>'); document.write(solveEquation("x=x+2")+'<br/>'); </script>
- Split the equation into 2 halves (LHS and RHS) by using “=” as delimiter
- Parse LHS and RHS separately and find out the x coefficients and constant values on both sides
- Handle edge cases for “Infinite solutions” and “No solution” when either LHS = RHS or the values of LHS and RHS x coefficients and constants are equal or the final x coefficient after all the computation is zero respectively as seen in the code comments above.
- Lastly, compute the value of x by segregating x coefficients on LHS and constants on RHS, divide the constant on RHS with x coefficient on LHS to obtain the final value of x.