这是我使用@dasblinkenlight 技巧的变体编写的代码。
NSMutableArray *compareSets = [NSMutableArray new];
NSMutableArray *t = [@[ @[@1, @2, @3],@[@12,@13,@14,@15,@16], @[@2, @5, @6], @[ @8, @9], @[@10, @2, @9], @[@11,@12222], @[@123, @34, @342, @1000], @[@34, @10001] ] mutableCopy] ;
for (NSArray *m in t) {
NSMutableSet *b = [[NSMutableSet alloc] initWithArray:m];
[compareSets addObject:b];
}
int reRunSet = 0;
int runStore = 0;
while (true) {
int setCount = compareSets.count;
if (setCount == 1) {
break;
}
runStore = (int) setCount;
for (int i = (runStore - 1); i > 0; i--) {
if ( [compareSets[0] intersectsSet:compareSets[i]] ) {
setCount++;
[compareSets[i] unionSet:compareSets[0]];
[compareSets removeObjectAtIndex:0];
}
}
NSMutableSet *t = [[NSMutableSet alloc] init];
[t setSet:compareSets[0]];
[compareSets removeObjectAtIndex:0];
[compareSets addObject:t];
if (runStore != setCount) {
reRunSet = 0;
continue;
}
if (setCount == compareSets.count) {
reRunSet ++;
if (reRunSet == setCount) {
break;
}
}
}
NSLog(@"compared sets finish = %@", compareSets);