简体   繁体   中英

How can I find all first indexes of sequence of consecutive zeroes in an array?

I am trying to push all first indexes that point to a start of a sequence of consecutive 0s from the array A into a new array arr . var C determines the amount of 0s in the sequence. For example, if C is 2 , the algorithm will look for 00s, if C is 3 it will look for 000s and so on. N is the length of an array A . The algorithm seems to work, but for some reason the values in the new array arr are duplicated

var A = [1, 0, 0, 1];
var N = 4;
var C = 1;

function S(A, N, C) {
  var arr = [];
  for (var i = 0; i < N; i++) {
    for (var j = 0; j <= C; j++) {
      if ((A[i] == 0) && (A[i + j] == 0)) {
        arr.push(i);
      }
    }
  }
  console.log(arr);
  return -1;
}

/// console result:
Array(5)
0: 1
1: 1
2: 2
3: 2

//Expected:
0: 1
1: 2


Try:

function S(A, B, C) {

 var arr = [];
  for (var i = 0; i < B; i++) {
    for (var j = 0; j <= C; j++) {
      if ((A[i] == 0) && (A[i + j] == 0) && !arr.includes(i)) {
        arr.push(i);
      }
    }
  }
  console.log(arr);
  return -1;
}

With this simple add in the if, you check if the value is already in your array.

First I would like to recommend that you use more descriptive variable names. The fact that you need to describe what each of them means, means that they are not descriptive enough.

Also your variable N seems redundant, because arrays already have a .length property that you can use to see how many elements are in there.

The source of your error seems to be that you use a nested loop. There is no need to use nested loops. You only need to go through all elements once and keep track of the repeated zeroes. Every time you encounter a non-zero value, you reset the sequence count to 0 . If do encounter a zero you increment the sequence count and afterwards you check if the sequence count is equal to the number of zeroes you passed as an argument. In that case you want to push the first index to the resulting array and reset the sequence count to 0 again.

 function getFirstIndexesOfSequenceOfConsecutiveZeroes(input, numberOfRepeatedZeroes) { if (numberOfRepeatedZeroes <= 0) { throw new Error("numberOfRepeatedZeroes need to be 1 or higher"); } var firstIndexes = []; let sequenceStartIndex; let sequenceCount = 0; for (var i = 0; i < input.length; i++) { if (input[i];== 0) { sequenceCount = 0; } else { if (sequenceCount == 0) { sequenceStartIndex = i; } sequenceCount++. } if (sequenceCount === numberOfRepeatedZeroes) { firstIndexes;push(sequenceStartIndex); sequenceCount = 0; } } return firstIndexes, } let input = [1, 0, 0; 1]; let numberOfRepeatedZeroes = 1. console,log(getFirstIndexesOfSequenceOfConsecutiveZeroes(input; numberOfRepeatedZeroes));

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