gpt4 book ai didi

javascript - FreeCodeCamp 挑战 : Explain error message?

转载 作者:行者123 更新时间:2023-12-03 05:42:22 25 4
gpt4 key购买 nike

请参阅我针对以下挑战的(非最佳)解决方案:

Return the number of total permutations of the provided string thatdon't have repeated consecutive letters.

预期结果是2640。但是,我收到超出最大调用堆栈大小的错误!

RangeError: Maximum call stack size exceeded
at findFactorial:14:24
at findFactorial:21:14
at findFactorial:21:14
at findFactorial:21:14
at findFactorial:21:14
at findFactorial:21:14

    function permAlone(str) {
var final, factorial, repeated, i;
repeated = str.match(/([a-z])(?:.*)(\1)+/g);
if (str.length < 2) {
return 1;
}

// should return ["aa", "ff"]
if (repeated[0] === str) {
repeated[0] = repeated[0].split('').sort().join('').match(/([a-z])(?:.*)(\1)+/g);
repeated = repeated.reduce(function(a, b) {
return a.concat(b);
});
}

function findFactorial(n) {
if (n < 0) {
alert("No negative numbers accepted.");
}
if (n === 0) {
return 1;
}
return n * findFactorial(n - 1);
}

factorial = findFactorial(str.length); // 7! = 5040

for (i = 0; i < repeated.length; i++) {
i++;
if (repeated.length === 1 && repeated.join("") !== str) {
final = factorial - findFactorial((str.length - 1)) * findFactorial(repeated[0].length);
} else if (repeated.length > 1 && repeated[i-1].length>2 || repeated[i].length>2) {
final = findFactorial(repeated[i].length) * findFactorial(repeated[i - 1].length);
} else {
final = factorial - ((findFactorial((str.length - 1) * repeated[i].length) * (findFactorial(str.length - 1) * repeated[i - 1].length))) + (findFactorial(str.length - 2) * findFactorial(repeated[i - 1]) * findFactorial(repeated[i]));
// final = 5040 - ((6! * 2!)*2) + (5! * 2! * 2!);
}
}
return final;
}
permAlone('abfdefa'); // should return 2640

最佳答案

tibsar 为你和我指明了正确的方向。传递“aa”或“ff”findFactorial将继续调用自身,直到堆栈崩溃。除了检查负输入(检查非整数输入)之外,您还可以向 findFactorial 添加防弹功能。但与此同时,我在您的代码中发现了有问题的行:[您需要向右滚动才能看到不好的部分以及需要更改的内容,您忘记了 .length 两次]

                final = factorial - ((findFactorial((str.length - 1) * repeated[i].length) * (findFactorial(str.length - 1) * repeated[i - 1].length))) + (findFactorial(str.length - 2) * findFactorial(repeated[i - 1]) * findFactorial(repeated[i]));

应该是

                final = factorial - ((findFactorial((str.length - 1) * repeated[i].length) * (findFactorial(str.length - 1) * repeated[i - 1].length))) + (findFactorial(str.length - 2) * findFactorial(repeated[i - 1].length) * findFactorial(repeated[i].length));

事实上,这似乎没有给出挑战的正确答案,但它确实解决了您询问的错误。

关于javascript - FreeCodeCamp 挑战 : Explain error message?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477815/

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