函数返回正确,但在while循环中超时,即使条件最终变为false

时间:2018-05-23 19:56:14

标签: javascript while-loop timeout

尝试执行kata并且我的函数正确返回所有内容,但是我收到测试输出错误,告诉我它在12000 ms时超时,尽管所有测试都通过并完成。我怀疑while循环是罪魁祸首,但我放入了两个地方,while循环条件将转为false并停止。有人可以指出我为什么这个函数除了超时之外还能正常工作的方向吗?

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;
}

1 个答案:

答案 0 :(得分:0)

基本上katas依赖于速度,这意味着最好不要使用数组方法,如reduce或数组变异函数,如shift

速度(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; }