Solving linear equations and similar algebra problems using JavaScript

I am new to JavaScript and I am trying to write a simple script that solves linear equations. So far, my script solves linear equations that are plus and minus, such as "2x + 28 - 18x = 36 - 4x + 10". I want him to also be able to solve problems of linear equations / algebras that contain multiplication and division, such as "2x * 3x = 4 / 2x".

I have an idea of ​​what to do next, but I think that the script for me now may be too complicated, and it is only more difficult to add multiplication and division.

Below is my script. I hope for a few pointers on how I could improve and simplify what I already have, and what is the best way to add multiplication and division?

My script on JS Bin: http://jsbin.com/ufekug/1/edit

My script:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Problem Solver</title> <script> window.onload = function() { // Total Xs on each side of equation // Example problem: 5x + 2 = 10 - 2x var leftSideXTotal = 0; // 5 var rightSideXTotal = 0; // -2 // Total integers on each side of equation // Example problem: 5x + 2 = 10 - 2x var leftSideIntTotal = 0; // 2 var rightSideIntTotal = 0; // 10 // Enter a math problem to solve var problem = "5x + 2 = 10 - 2x"; // Remove all spaces in problem // Example problem: 5x + 2 = 10 - 2x problem = problem.replace(/\s/g,''); // 5x+2=10-2x // Add + signs in front of all - signs // Example problem: 5x + 2 = 10 - 2x problem = problem.replace(/-/gi, "+-"); // 5x+2=10+-2x // Split problem into left and right sides // Example problem: 5x + 2 = 10 - 2x var problemArray = problem.split("="); var problemLeftSide = problemArray[0]; // 5x+2 var problemRightSide = problemArray[1]; // 10+-2x // Split values on each side into an array var problemLeftSideValues = problemLeftSide.split("+"); var problemRightSideValues = problemRightSide.split("+"); // Go through the left side values and add them up for (var i = 0; i < problemLeftSideValues.length; i++) { // Current value var currentValue = problemLeftSideValues[i]; // Length of current value var currentValueLength = currentValue.length; if (currentValue.charAt(currentValueLength - 1) == "x") { //Check if current value is a X value // Remove X from end of current value currentValue = currentValue.split("x"); // Add to total Xs on left side leftSideXTotal = Number(leftSideXTotal) + Number(currentValue[0]); } else { // Add to total integers on left side leftSideIntTotal = Number(leftSideIntTotal) + Number(problemLeftSideValues[i]); } } // Go through the right side values and add them up for (var i = 0; i < problemRightSideValues.length; i++) { // Current value var currentValue = problemRightSideValues[i]; // Length of current value var currentValueLength = currentValue.length; if (currentValue.charAt(currentValueLength - 1) == "x") { //Check if current value is a X value // Remove X from end of current value currentValue = currentValue.split("x"); // Add to total Xs on right side rightSideXTotal = Number(rightSideXTotal) + Number(currentValue[0]); } else { // Add to total integers on right side rightSideIntTotal = Number(rightSideIntTotal) + Number(problemRightSideValues[i]); } } // Compute var totalXs = (leftSideXTotal - rightSideXTotal) var totalIntegers = (rightSideIntTotal - leftSideIntTotal) var solution = (totalIntegers / totalXs) // Display solution document.getElementById("divSolution").innerText = solution; } </script> </head> <body> <div id="divSolution"></div> </body> </html> 
+7
source share
2 answers

You need to write (or use) a parser with operator precedence.

The idea is to turn the equation into a tree, for example.

 x + 3 = 3x - 2 

Is really a structure

  = / \ + - / \ / \ x 3 * 2 / \ 3 x 

Where each statement describes an operation between two "branches" of a tree. Using a javascript object, creating a structure is easy.

 function tree(lterm,op,rterm) { t.operator = op; t.left = lterm; t.right = rterm; return t; } expression = tree("x", "/", tree("x","+",3) ); // x / (x+3) 

Then, by manipulating the tree, you can solve the equation or perform calculations. To evaluate an expression (without any unknowns), you run a tree starting at the terminals and up from intersection to intersection. You can replace a section of a tree with a result or annotate it with a result - add a result variable to the tree object.

Here are some useful methods to include in a tree class:

  • getLeft
  • Getright
  • prettyPrint
  • estimate
  • rate ("x", 5) // x = 5, now rate ...

These are not just linear operations that can be β€œparsed” in this way. The best parsers will have a list of operators, which includes = * / + - but also unary operators: - () sin cos ...

I did not use operator syntax parser in javascript, but some of them must exist in advance. Of course, a good soul on this site will add a good link or two to my answer.

By the way, the tree-based approach has many applications. In a spreadsheet:

 A2 = A1+B1 

In a boolean solver:

 A = not (B or C) C = true 

In XML parsing:

 <main> <part>A</part> <part>B</part> </main> 
+6
source

I defined two functions:

getTotalX() : it will give you the x count for any input string.

getTotalScalars() : it will give you the total number of scalars (numbers).

And finally, your updated code (it still only does addition and subtraction):

 <script> window.onload = function() { // Total Xs on each side of equation // Example problem: 5x + 2 = 10 - 2x var leftSideXTotal = 0; // 5 var rightSideXTotal = 0; // -2 // Total integers on each side of equation // Example problem: 5x + 2 = 10 - 2x var leftSideIntTotal = 0; // 2 var rightSideIntTotal = 0; // 10 // Enter a math problem to solve var problem = "5x + 2 = 10 - 2x"; // Remove all spaces in problem // Example problem: 5x + 2 = 10 - 2x problem = problem.replace(/\s/g,''); // 5x+2=10-2x // Add + signs in front of all - signs // Example problem: 5x + 2 = 10 - 2x problem = problem.replace(/-/gi, "+-"); // 5x+2=10+-2x // Split problem into left and right sides // Example problem: 5x + 2 = 10 - 2x var problemArray = problem.split("="); var problemLeftSide = problemArray[0]; // 5x+2 var problemRightSide = problemArray[1]; // 10+-2x leftSideXTotal = getTotalX(problemLeftSide); leftSideIntTotal = getTotalScalars(problemLeftSide); rightSideXTotal = getTotalX(problemRightSide); rightSideIntTotal = getTotalScalars(problemRightSide); // Compute var totalXs = (leftSideXTotal - rightSideXTotal) var totalIntegers = (rightSideIntTotal - leftSideIntTotal) var solution = (totalIntegers / totalXs) // Display solution document.getElementById("divSolution").innerText = solution; // Find the total number of X in the string function getTotalX(data) { data = data.replace(/\s/g,''); xCount = 0; if(data.indexOf('x') != -1) { if (data.indexOf('+') != -1) { data = data.split('+'); for(var i = 0; i < data.length; i++) { xCount += getTotalX(data[i]); } } else if (data.indexOf('-') != -1) { data = data.split('-'); // Single negative if(data[0] == "") { xCount -= getTotalX(data[1]); } else { xCount += getTotalX(data[0]); for(var i = 1; i < data.length; i++) { xCount -= getTotalX(data[i]); } } } else { xCount = parseInt(data.split('x')[0]); } } return xCount; } // Find the total of scalars function getTotalScalars(data) { data = data.replace(/\s/g,''); intCount = 0; if (data.indexOf('+') != -1) { data = data.split('+'); for(var i = 0; i < data.length; i++) { intCount += getTotalScalars(data[i]); } } else if (data.indexOf('-') != -1) { data = data.split('-'); // Single negative if(data[0] == "") { intCount -= getTotalScalars(data[1]); } else { intCount += getTotalScalars(data[0]); for(var i = 1; i < data.length; i++) { intCount -= getTotalScalars(data[i]); } } } else { if(data.indexOf('x') == -1) { intCount = parseInt(data.split('x')[0]); } else { intCount = 0; } } return intCount; } } </script> 
0
source

All Articles