简体   繁体   中英

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

The speed (694 ms) comes from a simple for loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM