Objective-C: Finding the amount of times an Object occurs in an Array with indexes [duplicate]
I need a way of counting how many time an object occurs in any given MutableArray and then returning the indexes of the objects into a seperate Mutable Array. Ive tried doing this a couple of ways but cant figure it out.
So basically say I have an array containing 2,3,3,4,3,5,3 When searching for 3, it should give me both the number of times, 4, and a seperate array containing 1,2,4,6 (the indexes of the objects.
I saw the following code already here on the site, but cant work out how to modify it, can anyone help me?
int occurrences = 0;
for(NSString *string in array){
occurrences += ([string isEqualToString:@"Apple"]?1:0); //certain object is @"Apple"
}
int occurrences = 0;
NSMutableArray *indices = [NSMutableArray array];
int i = 0;
for (i = 0; i < [array count]; i++) {
NSString *obj = [array objectAtIndex:i];
if ([obj isEqualToString:@"Apple"]) {
occurrences++;
[indices addObject:[NSNumber numberWithInt:i]];
}
}
You also could drop the tracking with occurrences
and do something like
int occurrences = [indices count];
after the for
loop.
id thingYouAreLookingFor;
NSIndexSet *result = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [thingYouAreLookingFor equals: obj];
}];
Easy way to do it if you don't mind time, it's a square time operation.
- Keep a counter, recording how many elements from array1 has appeared in array2
- for all element in array1, test if it exist in array2. If it exist, counter++, if not, continue.
- return the counter.
Use [myMutableArray containsObject:parameter]
to return a boolean of wether array2 contains an element or not.
精彩评论