Return all sets where all its numbers are not in another set

Recently, I had to solve the following algorithm issue, which confused me.

Suppose you have an array of sets containing integers. Write a function that returns all sets, where all its numbers are not in any other set.

EXAMPLE {0,4,9}, {3,4,5}, {6,7,8}

RESULT {6,7,8}

The code must be in Objective-C or Swift.

[EDIT]

I have come up so far with something similar, but I can’t finish it.

- (NSArray*) getDisjointedSets:(NSArray*)sets { NSArray* resultedSet; NSMutableArray* indexDoesntExistInSets = [NSMutableArray array]; [sets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSArray* nextIndexArray = [sets objectAtIndex:idx+1]; NSNumber* numberIndex = obj; [nextIndexArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSNumber* numberNextIndex = obj; if (numberIndex.intValue == numberNextIndex.intValue) { // number exists in the next set, continue *stop = YES;; } else { [indexDoesntExistInSets addObject:numberIndex]; } }]; }]; return resultedSet; } 
+6
source share
1 answer

Your code iterates through an array of arrays. But then you get the next array, repeat its numbers, but try to compare each of these numbers with the current set.

Assuming you have an NSArray objects, you can do this:

 - (NSArray *)getDisjointedSets:(NSArray *)sets { NSMutableArray *resultSet = [NSMutableArray array]; for (NSArray *arrayA in sets) { BOOL noMatch = YES; for (NSArray *arrayB in sets) { // Skip if both are the same array if (arrayA != arrayB) { NSMutableSet *setA = [NSMutableSet setWithArray:arrayA]; NSSet *setB = [NSSet setWithArray:arrayB]; [setA intersectSet:setB]; if (setA.count) { // The two sets have something in common noMatch = NO; break; } } } if (noMatch) { [resultSet addObject:arrayA]; } } return resultSet; } 

Test code:

 NSArray *sets = @[ @[ @0, @4, @9 ], @[ @3, @4, @5 ], @[ @6, @7, @8 ] ]; NSArray *result = [self getDisjointedSets:sets]; NSLog(@"results = %@", result); 
0
source

Source: https://habr.com/ru/post/986685/


All Articles