Search code examples
javascriptparsingvariablesalgebra

Is it possible to convert A string that is an equation with a variable into a equation?


I need to convert a string returned from prompt into an equation, however the parseFloat returns as only the first number, and symbols in an equation, and stops at the variable. The variable will always = x. The program is designed to convert an algebraic expression say 15*x(5^4-56)*17/x=15 into an expression, and calculate the value of x. If someone could show me how to do this, it would help dramatically. I am currently using multiple prompts, having the user put in the equation before x, then the equation after x, then it inserts a variable in between the two, and calculates it's value.

Edit:

I have no variables predefined, and it must work in equations where x > 1000, or x != //an integer.

Thanks in advance!


Solution

  • Seems to be a complex problem...

    This is a solution for a simple relaxed version of your problem. Hope you can use some components of this.

    Constraints:

    1. answer for x should be integers between 0 and 1000
    2. the left hand side of the expression should be proper javascript syntax

    var input = prompt("enter the equation");  //eg: x*x+x+1=241
    var parts = input.split('=');
    
    //solving equation starts
    var x = 0;
    var temp = eval(parts[0]);
    while (temp != parts[1] && x<1000){
       x++;
       temp = eval(parts[0]);
    }
    var ans = (x<1000)?"answer is "+x:"this program cannot solve this";
    //solving equation finishes
      
    alert(ans);

    You can replace the "solving equation" part with some numerical methods used in computer science to solve equations (more details here) . You will have to parse the left side of equation and map them to proper javascript expressions (as a string to execute with eval()) if you want to allow users to use your syntax.