Thread: density of 0s & 1s in an array

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    12

    density of 0s & 1s in an array

    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.

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    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.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multidimensional Array Addressing
    By BlackOps in forum C Programming
    Replies: 11
    Last Post: 07-21-2009, 09:26 PM
  2. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  3. [question]Analyzing data in a two-dimensional array
    By burbose in forum C Programming
    Replies: 2
    Last Post: 06-13-2005, 07:31 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM