2013-01-07 2 views
7

저는 JavaScript가 처음이므로 선형 방정식을 해결하는 간단한 스크립트를 작성하려고합니다. 지금까지 필자의 스크립트는 "2x + 28 - 18x = 36 - 4x + 10"과 같은 양수의 선형 방정식을 풀었다. 나는 또한 "2x * 3x = 4/2x"와 같은 곱셈과 나눗셈을 포함하는 선형 방정식/대수학 문제를 풀 수 있기를 바랍니다.선형 방정식 및 JavaScript로 유사한 대수 문제 해결

나는 다음에해야 할 일에 대한 아이디어를 가지고 있지만, 지금은 스크립트가 너무 복잡하고 곱셈과 나눗셈을 추가하는 것이 더 복잡 할 것이라고 생각합니다.

아래는 내 스크립트입니다. 나는 내가 가지고있는 것을 향상시키고 단순화하는 방법과 곱셈과 나눗셈을 추가하는 가장 좋은 방법에 대한 몇 가지 조언을 원하고있다. JS 빈에

내 스크립트를 http://jsbin.com/ufekug/1/edit

내 스크립트를

getTotalX() : 나는 두 가지 기능을 정의

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

입니다. 자바 스크립트 객체를 사용하면이 구조를 만드는 데 어렵지 않을해야합니다

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, 지금 평가 ...

그것은 단지 이런 방식으로 "파싱"될 수있는 선형 작업을 수행합니다.더 나은 파서에는 = */+를 포함하는 연산자 목록이 있지만 단항 연산자도 포함됩니다. ... (0120) . 확실히이 사이트의 친절한 영혼은 제 대답에 좋은 링크를 추가 할 것입니다.

그런데 트리 방식에는 많은 응용 프로그램이 있습니다. 부울 솔버에서

A2 = A1+B1 

:

A = not (B or C) 
C = true 

XML 파싱에서 : 스프레드 시트에서

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

그것은 모든 입력 문자열을 당신에게 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>