Created
February 27, 2014 00:52
-
-
Save akhenakh/9242055 to your computer and use it in GitHub Desktop.
Unoptimized Permut
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// unoptimized permute pair elements avoiding repetitions | |
- (NSArray *) permuteArrayOfSets:(NSArray *)elements { | |
NSMutableSet *resultSet = [NSMutableSet set]; | |
for (NSUInteger i=0;i<[elements count]; i++) { | |
for (NSUInteger j=0;j<[elements count]; j++) { | |
if (i == j) continue; | |
NSSet *newSet = [NSSet setWithObjects:elements[i], elements[j], nil]; | |
if ([resultSet containsObject:newSet]) continue; | |
[resultSet addObject:newSet]; | |
} | |
} | |
return [NSArray arrayWithArray:[resultSet allObjects]]; | |
} | |
// merge set if one of the obj contained in the sets is in another set of elements | |
- (NSArray *) mergeArrayOfSets:(NSArray *)elements { | |
if ([elements count] < 2) return elements; | |
// makes all sets mutable | |
NSMutableArray *srcArray = [NSMutableArray arrayWithCapacity:[elements count]]; | |
for (NSSet *s in elements) { | |
[srcArray addObject:[NSMutableSet setWithSet:s]]; | |
} | |
// add first obj to resArray | |
NSMutableArray *resArray = [NSMutableArray array]; | |
NSSet *oneSet = [srcArray lastObject]; | |
[resArray addObject:oneSet]; | |
[srcArray removeObject:oneSet]; | |
NSMutableArray *remainSets = [NSMutableArray array]; | |
// iterate over srcArray test if one elements from s is in resArray | |
for (NSMutableSet *outSet in srcArray) { | |
BOOL found = NO; | |
for (NSMutableSet *testSet in resArray) { | |
if ([outSet intersectsSet:testSet]) { | |
[outSet addObject:testSet]; | |
found = YES; | |
break; | |
} | |
} | |
if (!found) { | |
for (NSMutableSet *testSet in remainSets) { | |
if ([outSet intersectsSet:testSet]) { | |
[outSet addObject:testSet]; | |
found = YES; | |
break; | |
} | |
} | |
} | |
//otherwise add to remainsArray | |
if (!found) { | |
[remainSets addObject:outSet]; | |
} | |
}; | |
[resArray addObjectsFromArray:remainSets]; | |
return resArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment