golibrary avatar

Algorithm to solve linear equation in one variable

golibrary

Published: 12 Apr 2020 › Updated: 12 Apr 2020Algorithm to solve linear equation in one variable

Algorithm to solve linear equation in one variable


Problem Statement

Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.

If there is no solution for the equation, return "No solution".

If there are infinite solutions for the equation, return "Infinite solutions".

If there is exactly one solution for the equation, we ensure that the value of x is an integer.

Example 1:

Input: "x+5-3+x=6+x-2"

Output: "x=2"

Example 2:

Input: "x=x"

Output: "Infinite solutions"

Example 3:

Input: "2x=x"

Output: "x=0"

Example 4:

Input: "2x+3x-6x=x+2"

Output: "x=-1"

Example 5:

Input: "x=x+2"

Output: "No solution"

Javascript solution using regex below:-

<html>
<input type = "label"/>Enter expression of the form x+4x+5-6=8+x
<input type = "text" id="equation" maxlength="100" placeholder="Enter expression"/><br/>
<input type = "button" value="compute" onclick="solveEquation(document.getElementById('equation').value)"/>
</html>

<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];
}

</script>

 

Explanation:

  • 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.
 

The time complexity of the above algorithm is in the order of O(N).

Subscribe and follow Golibrary on Facebook and Linkedin to get all the updates.

Leave Algorithm to solve linear equation in one variable to:

Written by

Read more #steempress posts


Best Posts From golibrary

We have not curated any of golibrary's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From golibrary