Counting a range of Objects within a Subset of NSSet

165 views Asked by At

I have created several NSSet's with specific coordinates likes so:

CoordRange     = [[NSSet alloc] initWithObjects:[NSNumber numberWithInt:-1],
                 [NSNumber numberWithInt:-3],[NSNumber numberWithInt:-7],
                 [NSNumber numberWithInt:-5],nil];

I will receive several coordinates within an NSArray. I create an NSSet from the array (GRID) to use the "isSubsetOfSet" function of NSSet. It is possible that the new NSSet (GRID) can contain a value outside CoordRange. Is there a way for me to determine if GRID contains at least four values from CoordRange.

So if GRID = [-1,-5,-7,-3,10], is there a way for me to determine if at least four of the values are a subset of CoordRange? The isSubSetOfSet will only compare the entire set/range.

1

There are 1 answers

0
Yan On BEST ANSWER

This might not be the most efficient solution but you can iterate through the Set and check if each object is in the second set until you have 4 objects.

NSSet *coordRange     = [[NSSet alloc] initWithObjects:[NSNumber numberWithInt:-1],
                  [NSNumber numberWithInt:-3],[NSNumber numberWithInt:-7],
                  [NSNumber numberWithInt:-5],nil];
NSSet *grid = [NSSet setWithArray:@[@-1,@-2,@-7,@-3,@10]];

__block NSInteger count = 0;

[grid enumerateObjectsUsingBlock:^(id  _Nonnull obj, BOOL * _Nonnull stop) {
    if ([coordRange containsObject:obj]) count++;
    if (count >= 4) *stop = YES;
}];

NSLog(@"count: %lu", count);