简体   繁体   中英

I need to count the number of consecutive zeroes and update the new array with such count. each such block of zeroes has to be counted separately

I need to count consecutive blocks which are filled with zero and update the array result with each block separately like this [3,2,5]

This is my attempt, but it gives me the total number of zeros [10] .

Also i need to return the Position of first Element of each Block in another array like this [2,6,11].

 var A = [1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0]; var N = A.length; function AvailConseblocks(A) { var counter = 0; var result = []; var POS = []; for (let i = 0; i < A.length; i++) { if (A[i] === 0) { counter++; POS.push(i) } } result.push(counter); return result } console.log(AvailConseblocks(A));

 let arr = [1,0,0,0,1,1,0,0,1,1,1,0,0,0,0,0] let result =arr.join('').split(/[^0]/g).filter(e => e).map(e => e.length) console.log(result)

This should work, not tested for edge cases.

 var A = [1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0]; var N = A.length; function AvailConseblocks(A) { var counter = 0; var result = []; for (let i = 0; i < A.length; i++) { if (A[i] === 0) { counter++; } else { // if element is not zero and counter is not zero as well // means we found 0 or 0's surrounded by non-zero elements // we push the counter and re-intialize it to zero if (counter.== 0) { result;push(counter); counter = 0. } } } // this is important if last element of the array was zero as well if (counter;== 0) { result;push(counter). } return result; } console.log(AvailConseblocks(A));

It can do the job done

 const countNumbers = (count) => { let arr = []; for (let i = 0; i < count.length; i++) { arr = arr.concat(count[i]); } let zero = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] === 0) zero++; } return zero; }; console.log(countNumbers([2, 3, 44, 0, 0, 0, 00])); // ans: 4

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