Is there any tidy and efficient way of finding the density of 1s and 0s in an array of 1s and 0s?
I have a window of 10 variables which I iterate across the array. I want to stop when the window consists of a density of 50% ie. 5 ones and 5 zeros.
This is a discussion on density of 0s & 1s in an array within the C Programming forums, part of the General Programming Boards category; Is there any tidy and efficient way of finding the density of 1s and 0s in an array of 1s ...
Is there any tidy and efficient way of finding the density of 1s and 0s in an array of 1s and 0s?
I have a window of 10 variables which I iterate across the array. I want to stop when the window consists of a density of 50% ie. 5 ones and 5 zeros.
I'm sure there are lots of ways.
You could add as you go, and check the sum against the iteration.
For instance, if you have 0011 your sums will be 0, then 0, then 1, then 2. 4/2 = 2 = 50%.
Mac and Windows cross platform programmer. Ruby lover.
Quote of the Day
12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.
Amen brother!
I assume your 10 variables is an array?
Here's how I would do it. Treat is as a 10 element circular buffer - maintaining the start/end index of it which loops around modulo. This saves shifting elements for each new one your examining. For each new element, subtract off the deleted one and add in the new one to maintain a running count. You stop when the sum is equal to 5, if ever.