获得代数项的系数

时间:2017-04-17 03:34:14

标签: javascript regex math

给定一个代数项的输入,我试图得到变量的系数。输入中唯一的运算符是+ -,只有一个变量。

示例:

2x^2+3x+4 => [ 2, 3, 4 ]

3-x => [ -1, 3 ]

x^2+x => [ 1, 1, 0 ]

x+x^3 => [ 1, 0, 1, 0 ]

输入无效:

2x^2+2x^2

这是我第一次尝试:

var str = " 2x^4-1+9x^3-100x^2";

    function getCoeff(term) {

        var nterm = (term.replace(/[^0-9|-]x(?!\^)/g,"1x")).replace(/[^0-9|\+]x(?!\^)/g,"-1x"); // ==> Replace ‘-/x’ with ‘-/1x’

        for ( var i = 0; i < 10; i++ ) { // ==> Loop true the regexs to replace all ‘x^n’ to ‘1x^n’

            var re = new RegExp('[^0-9|\-]x\\^' + i); // ==> Regex for x^n
            var re2 = new RegExp('[^0-9|]x\\^' + i); // ==> Regex for -x^n

            nterm = (nterm.replace(re,"1x^" + i)).replace(re2,"-1x^" + i); }

        for ( var m = 10; m > 1; m--  ) { // ==> Get the coefficients of ax^n in descending order
            var re3 = new RegExp('\\W?\\d+(?=x\\^' + m + ')' ); 
            if ( nterm.match(re3) === null ) {
                var result = "";
            } else {
                result += ((nterm.match(re3)+', ').toString()).replace(/\+/g,""); }}

        if ( nterm.match(/\W?\d+(?=x(?!\^))/g) === null ) { // Regex for coefficient x
            var result2 = "";
        } else {
            result2 = ((nterm.match(/\W?\d+(?=x(?!\^))/g)).toString()).replace(/\+/g,"") + ',';  }

        if ( nterm.match(/[^\^]\d+(?!\d|x)/g) === null ) { // Regex for constant
            var result3 = "";
        } else {
            result3 = ((nterm.match(/[^\^]\d+(?!\d|x)/g)).toString()).replace(/\+/g,""); }

        console.log(('[' + ' ' + result + result2 + ' ' + result3 + ']' ).replace(/\s/g,"")); }

    getCoeff(str)

问题:

  • 缺少x term时不起作用。

例如:x^4 + x + 1 ==> Expected: [1, 0, 0, 1, 1] ==> Actual: [ 1, 1 ]

  • x应返回[ 1,0 ],但会返回[ 1, ]

这是我的第二次尝试。

var str = "-999x^2+x^3+x+3";
function getCoeff(string) {
if ( string.charAt(0) === 'x' ) { // If the first term is x, because of my regex it needs a space to match it
    string = ' ' + string;
}

for ( var i = 0; i < 10; i++ ) { // ==> Loop true the regexs to replace all ‘x^n’ to ‘1x^n’

    var re = new RegExp('[^0-9|\-]x\\^' + i);
    var re2 = new RegExp('[^0-9|]x\\^' + i);
    string = (string.replace(re,"+1x^" + i)).replace(re2," -1x^" + i); } 

var final = string.replace(/-/g,'+-'); // ==> Spilt(‘x’) later so to retain the -ve sign

final = (final.replace(/[^0-9|-]x(?!\^)/g,"+1x")).replace(/[^0-9|+]x(?!\^)/g,"-1x");  // ==> Replace ‘-/x’ with ‘-/1x’

final = final.replace(/[^\^](\d+(?!\d|x))/g,'+$1x^0'); // ==> Replace ‘c’ with ‘cx^0’
final = final.replace(/x(?!\^)/g, "x^1"); // ==> Replace ‘x’ with ‘x^1’
final = final.split('+'); // ==> Right now array looks something like this [ ax^(n), bx^(n-1), … yx^1,  zx^0]
final = final.filter(function(entry) { return entry.trim() !== ''; }); // Sorts array by the number behind in descending order

var reS = /^-?\d+/,
    reE = /\d+$/;
var result = final.sort(function(a, b) {
    a = reE.exec(a);
    b = reE.exec(b);
    return b - a;
}).reduce(function(res, str, i) {
    var gap = reE.exec(final[i - 1]) - reE.exec(str);
    if(gap > 0)
        while(--gap) res.push(0);
    res.push(+reS.exec(str));
    return res;
}, []); // Return the coefficients
console.log("Result:", result); 
}

getCoeff(str);

问题:

  1. 有没有办法在不使用正则表达式的情况下完成?

  2. 如何解决此问题?当没有常数术语时

    getCoeff(“x^3”) ==> [ 1 ] , when it should give [ 1, 0, 0 ]

  3. 如何让我的代码更有效率?

  4. 如何使用正则表达式匹配x^n条款但不匹配-x^n条款?这是我现在的一个:[^0-9|\-]x\\^' + i,但它需要一个空格。

  5. 参考:

    How to sort array based on the numbers in string?

1 个答案:

答案 0 :(得分:1)

function getCoef(str) {
  str = str.replace(/\s+/g, "");                   // remove spaces (optional)
  
  var parts = str.match(/[+\-]?[^+\-]+/g);         // get the parts: see explanation bellow

  // accumulate the results
  return parts.reduce(function(res, part) {        // for each part in parts
    var coef = parseFloat(part) || +(part[0] + "1") || 1;// the coeficient is the number at the begining of each part (34x => 34), if there is no number it is assumed to be +/-1 depending on the sign (+x^2 => +1)
    var x = part.indexOf('x');                     // the index of "x" in this part (could be -1 if there isn't)
    // calculating the power of this part
    var power = x === -1 ?                         // if the index of "x" is -1 (there is no "x")
                  0:                               // then the power is 0 (Ex: -2)
                  part[x + 1] === "^" ?            // otherwise (if there is an "x"), then check if the char right after "x" is "^", if so...
                    +part.slice(x + 2) :           // then the power is the number right after it (Ex: 55x^30)
                    1;                             // otherwise it's 1 (Ex: 55x)
    res[power] = (res[power] || 0) + coef;         // if we have already encountered this power then add this coeficient to that, if not then just store it 
    return res;
  }, {});
}

/** TESTS **/
[
  "-999x^2 + x^3 + x + 3", "5x + 3 - 10x", "55x^3 + 1", "55.12x^4 + 20x^4 - 120x^4"
].forEach(function(test) {
  console.log(test, "=>", getCoef(test));
});

输出:

函数getCoef的结果将是这种格式的对象:

{
    "power": "coeficient",
    "other power": "other coeficient",
    ...
}

<强>解释

  1. str = str.replace(/\s+/g, "");
  2. 删除空格(显而易见)。

    1. var parts = str.match(/[+\-]?[^+\-]+/g);
    2. 将字符串拆分为多个部分。字符串"-5x^2-3+10x"将返回["-5x^2", "-3", "+10x"]。正则表达式将寻找:

      [+\-]?  : a "+" or "-" sign (if any)
      [^+\-]+ : anything that isn't a "+" nor "-" (get everything up until the new + or - or the end is reached)
      g       : to get all parts
      
      1. var coef = parseFloat(part) || +(part[0] + "1") || 1;
      2. 使用以下方法获取此部分的系数:

        parseFloat     : for parts that have a number before "x" like: "+55x", "-34.22x^11", "5x", ...
        +(part[0] + 1) : for parts that have only a sign like: "+x", "-x^2", ... (get the sign part[0] concatinate it with "1" and then cast the result into a number using binary +)
        1              : for parts that doesn't have a number nor a sign like "x^3", "x", ...
        

        请注意,"0x^4"之类的部分将被假定为使用上述系数为1(但我不明白为什么人们无论如何都需要一个空系数)!

        1. var x = part.indexOf('x');
        2. 获取部件中的字符"x"的索引,以区分具有"3x""x^11",......和不喜欢{{1}的部分的部分,},

          1. "+5"
          2. 如果部件(var power = ...)中没有"x",则此部件的功效为x === -1

            否则(0存在),然后我们检查"x""x")之后的字符是否为part[x + 1],如果是,那么权力就是whaterver之后的数字(剪切字符串"^"的那一位并使用一元part.slice(x + 2)将其转换为数字),如果+之后没有"^",则权力是"x"

            1. 1
            2. 将刚刚计算出的系数res[power] = (res[power] || 0) + coef;添加到此权力的已累计系数中(如果没有累积则使用coef)。

              此行可以简化为:

              0

              这使得可以在同一个字符串中包含多次相同的功率,例如:if(res[power]) // if we already encountered this power in other parts before res[power] += coef; // then add this coeficient to the sum of those previous coeficients else // otherwise res[power] = coef; // start a new sum initialized with this coeficient ,...

              将结果对象转换为所需的数组:

              那样:

              "5x + 10x + 1 + x"

              将是:

              {
                  "3": 7,
                  "0": 19
              }
              

              [7, 0, 0, 19]