tags:

views:

93

answers:

6

I have an NSArray populated with 0's and 1's. How can I return the number of 0's in the array?

Thanks!

+1  A: 

Declare a counter, set it to 0, loop through the array and if the element is 0, increment the counter.

Lou Franco
Beat me by 45s -- but I posted code :)
Shaggy Frog
+4  A: 

Iterate through the array and count the things you're looking for.

Assuming you have an NSArray populated with NSNumbers:

NSArray* array = ... ; // populate array
NSUInteger count = 0;
for (NSNumber* number in array)
{
    if ([number intValue] == 0)
    {
        count++;
    }
}
Shaggy Frog
+4  A: 

A little perverted solution :)

NSUInteger zeros_count(NSArray *array) {
  NSUInteger sum = 0;
  for (NSNumber *number in array)
    sum += [number intValue];
  return [array count] - sum;
}
Vadim Shender
I love it. I want to use it to mess with my co-workers' minds.
No one in particular
+6  A: 

Depending on your application, you might consider using an NSCountedSet.

When it comes time to get the count of a certain type of object, you can just use the countForObject: instance method.

Probably a little too heavy for your current problem, but may be useful for others looking for similar solution.

Reed Olsen
This is precisely what NSCountedSet is for. You can make one from an array with `[[NSCountedSet alloc] initWithArray:array]` — then you can ask it for the count of any object in the array.
Chuck
A: 
NSArray* array = [[NSArray alloc] ...]; ; // put data into the array

NSUInteger arrayWithValue = 0;

for (NSNumber* number in array)

{

if ([number intValue] == NUMBERYOUARELOOKINGFOR)

    {
        count++;
    }
}
OOProg
Thanks Dave! I missed that :/
OOProg
+2  A: 

KeyValueCoding

int count = [array count] - [[array valueForKeyPath:@"@sum.intValue"] intValue];
jojaba