2013-01-07 21 views
7

私はJavaScriptを初めて使いました。私は線形方程式を解く簡単なスクリプトを書こうとしています。これまでのところ私のスクリプトは "2x + 28 - 18x = 36 - 4x + 10"のようなプラスとマイナスのみの線形方程式を解きます。私は、 "2x * 3x = 4/2x"のような乗算と除算を含む線形方程式/代数問題を解くこともできるようにしたい。線形方程式と同様の代数JavaScriptの問題を解決する

私は次のことを考えていますが、私は今のスクリプトが多すぎるかもしれないと思っています。そして、乗算と除算を追加するだけで複雑になります。

以下は私のスクリプトです。私は、私がすでに持っているものを改善し、単純化する方法と、乗算と除算を加えるための最良の方法についてのいくつかの指針を期待していますか?

JSビンのマイスクリプト:http://jsbin.com/ufekug/1/edit

マイスクリプト:

<!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> 
+0

これはかなり興味深い質問です。あなたがタイトルを短縮すれば、より多くの回答者を引き付けることができると思います。 –

+3

'2x * 3x = 4/2x'は実際に線形方程式ではありません。 – Rikonator

+0

編集されたタイトル。線形方程式を線形方程式および同様の代数問題に変更しました。 – user1822824

答えて

6

あなたが書く必要がある(または使用)オペレータ優先順位パーサ。

考え方は、等式をツリーに変換することです。

x + 3 = 3x - 2 

本当に構造、各オペレータが木の二つの「枝」間の動作を説明する

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

です。 JavaScriptのオブジェクトを使用すると、構造を作成することは困難ではありません。

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) 

はその後、ツリーを操作することによって、あなたは、方程式を解決する、または計算を実行することができます。式を(未知数なしで)評価するには、端末で始まり、交差点から交差点に向かってツリーを通過します。ツリーの一部を結果に置き換えるか、結果に注釈を付けて、結果変数をtreeオブジェクトに追加することができます。ここで

ツリークラスに含めるためにいくつかの便利なメソッドです:

  • getLeft
  • を評価GetRightの
  • prettyPrint
  • 評価( "X" を、5)// X = 5、今すぐ評価する ...

このように「解析」することができます。より良いパーサには、*/+を含む演算子のリストがありますが、単項演算子も含まれます: - ()sin cos ...

javascriptで演算子優先パーザを使用しませんでしたが、 。確かにこのサイトの親切な魂は、私の答えに良いリンクか2つを追加します。

ところで、ツリーアプローチには多くのアプリケーションがあります。ブールソルバーで

A2 = A1+B1 

:XML解析で

A = not (B or C) 
C = true 

:スプレッドシートで

<main> 
    <part>A</part> 
    <part>B</part> 
</main> 
0

私は2つの機能を定義しています

getTotalX():これは、任意の入力文字列のためにあなたにxのカウントを与えます。

getTotalScalars():スカラ(数値)を合計します。

そして最後に、あなたの更新されたコード(それはまだのみ加算と減算を行います):

<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> 
関連する問題