gpt4 book ai didi

javascript - 获取代数项的系数

转载 作者:行者123 更新时间:2023-11-29 23:48:01 26 4
gpt4 key购买 nike

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

例子:

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 项 时不起作用。

例如:x^4 + x + 1 ==> 预期:[1, 0, 0, 1, 1] ==> 实际:[ 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 ] ,什么时候应该给出 [ 1, 0, 0 ]

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

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

引用:

How to sort array based on the numbers in string?

最佳答案

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, "");:

删除空格(显而易见)。

  1. var parts = str.match(/[+\-]?[^+\-]+/g);:

将字符串拆分成多个部分。字符串 "-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(部分) || +(部分[0] + "1") || 1;:

使用以下方法获取这部分的系数:

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');:

获取字符"x"在部分中的索引,以区分有它的部分,如"3x""x^11", ... 和不喜欢 "+5", ...

的部分
  1. var power = ...:

如果部分 (x === -1) 中没有 "x",则该部分的幂为 0.

否则("x" 存在),然后我们检查 "x" 之后的字符是否(部分[x + 1]) 是 "^",如果是,则幂是它后面的任何数字(切掉字符串的那个位 part.slice(x + 2)并使用一元 + 将其转换为数字),如果 "x" 后没有 "^",则幂为 1

  1. 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]

var ret = { "3": 7, "0": 19 }; // the returned object

var powers = Object.keys(ret); // get all the powers (in this case [3, 0])

var max = Math.max.apply(null, powers); // get the max power from powers array (in this case 3)

var result = [];
for(var i = max; i >= 0; i--) // from the max power to 0
result.push(ret[i] || 0); // if that power has a coeficient then push it, otherwise push 0

console.log(result);

关于javascript - 获取代数项的系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43444749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com