[英]Function returns correctly, but times out in while loop even though condition eventually becomes false
Trying to do a kata and my function returns everything correctly, but I get an error for the test output telling me it timed out at 12000 ms despite all of the tests passing and completing. 尝试做一个kata ,我的函数正确地返回了所有内容,但是尽管所有测试都通过并完成了,但测试输出却出现错误,告诉我它在12000 ms超时。 I suspect the while loop is the culprit, but I have put in two places where the while loop conditional will flip to false and cease. 我怀疑while循环是罪魁祸首,但是我在两个地方放置了while循环条件将变为false并停止的地方。 Can somebody point me in the direction as to why this function works perfectly except for the timeout? 有人可以指出为什么该功能除了超时之外还能正常工作吗?
function beggars(values, n){
// Case if only one beggar
if (n == 1) {
const reducer = (accumulator, currentValue) => accumulator + currentValue;
let finalArr = [values.reduce(reducer)]
return finalArr;
}
// Case if more beggars than handouts
let remainder;
if (n > values.length) {
remainder = n - values.length;
n = values.length;
}
// Object creation
let obj = {};
let final = [];
for (var i = 1; i <= n; i++) {
obj[i] = 0;
}
// Populating object with data
let running = true;
while (running) {
for (var i = 1; i <= n; i++) {
let shift = values.shift()
obj[i] = obj[i] + shift;
}
if (values.length < n) {
for (var i = 1; i <= values.length + 1; i++) {
let shift = values.shift();
if (shift) {
obj[i] = obj[i] + shift;
}
running = false;
}
}
if (values.length == 0) {
running = false;
}
}
// Values of object into array
for (var key in obj) {
final.push(obj[key]);
}
// Pushing 0's for the left over beggars
if (remainder) {
for (var i = 0; i < remainder; i++) {
final.push(0);
}
}
return final;
}
Basically the katas rely on speed, that means it is better not to use the array methods, like reduce
or array mutating functions like shift
. 基本上,kata依赖于速度,这意味着最好不要使用数组方法,例如reduce
或数组变异函数(如shift
。
The speed (694 ms) comes from a simple for
loop. 速度(694 ms)来自简单的for
循环。
function beggars(values, n) { var result = Array.from({ length: n }).fill(0), // prefill array with zero i, l; for (i = 0, l = values.length; i < l; i++) { result[i % n] += values[i]; } return result; } console.log(beggars([1, 2, 3, 4, 5], 1)); // [15] console.log(beggars([1, 2, 3, 4, 5], 2)); // [9, 6] console.log(beggars([1, 2, 3, 4, 5], 3)); // [5, 7, 3] console.log(beggars([1, 2, 3, 4, 5], 6)); // [1, 2, 3, 4, 5, 0] console.log(beggars([1, 2, 3, 4, 5], 0)); // []
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.