Home > Net >  Resetting index in a for loop
Resetting index in a for loop

Time:06-12

This function needs to find the first occurrence of consecutive numbers whose sum equals 10, and return them as an array. My idea was to keep summing the numbers until the accumulator, in this case x becomes greater than 10, at which point the value of x is reset to zero, and i is reset back to index 1, by being assigned to the ct variable that is supposed to grow by one on each reset, so the loop would go back and start at the next element, until it gets the correct value. But for some reason ct is stuck at 1 and doesn't grow and the loop doesn't move past the second array element at index 1. Is there an error in the logic or the implementation?

Warning: This code may cause the page to crash or become unresponsive

const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];

function test(arr) {
  let x = 0;
  for (let i = 0; i < arr.length; i  ) {
    let ct = 0;
    x = x   arr[i]
    if (x > 10) {
      x = 0;
      i = ct;
      ct  
    }
    console.log(x)
  }
}

console.log(test(arr))

CodePudding user response:

The problem is that you've defined ct in the wrong place. It's inside the loop, meaning that every time you get to a point where i = ct, i is reset to 0 and ct has no effect (because every iteration, ct is reset to 0). You need to define ct in the same scope as x:

const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];

function test(arr) {

  let x = 0;
  let ct = 0;

  for (let i = 0; i < arr.length; i  ) {
    x = x   arr[i];

    if (x > 10) {
      x = 0;
      i = ct;
      ct  ;
    }

    console.log(x);
  }
}

test(arr);

I've also filled in the rest of the logic of the function for you in case you'd like it:

const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];

function test(arr) {

  let x = 0;
  let ct = 0;
  
  let result = [];

  for (let i = 0; i < arr.length; i  ) {
    x = x   arr[i];

    if (x > 10) {
      x = 0;
      i = ct;
      ct  ;
    }

    if (x == 10) {
      result = arr.slice(ct, i   1);
      return result;
    }

    console.log(x);
  }
  return result;
}

console.log(test(arr));

  • Related