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.
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%.
Mainframe assembler programmer by trade. C coder when I can.
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.