Maybe someone knows a simple algorithm for finding the number of '0' elements that are between '1' elements in an array?

Viewed 33

I need a simple algorithm to find the number of occurrences of 0 between 1 in an array, for example, after performing certain operations on these arrays:

var mas1 = [0,1,0,0,1]
var mas2 = [1,0,0,0,1]
var mas3 = [0,1,0,1,0]
var mas4 = [0,0,0,0,1]
var mas4 = [1,0,1,0,1]

We have to get:

result = 2
result = 3
result = 1
result = 0
result = 2

We can have any number of 1's or 0's in an unlimited array Any ideas?

1 Answers

You can continuously use indexOf to find the next 1 while accumulating the size of ranges in between consecutive ones.

let arr = [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1];
let count = 0;
for(let i = arr.indexOf(1); i != -1; ){
    const next = arr.indexOf(1, i + 1);
    if (next !== -1) count += next - i - 1;
    i = next;
}
console.log(count);

Related