我想在不同的elements
中找到arrays
的组合。假设我有三个NSArray
对象:
NSArray *set1 = [NSArray arrayWithObjects:@"A",@"B",@"C", nil];
NSArray *set2 = [NSArray arrayWithObjects:@"a",@"b", nil];
NSArray *set3 = [NSArray arrayWithObjects:@"1",nil];
现在所需的答案是以下数组
NSArray *combinations = [{A},{B},{C},{a},{b},{1},{A,a},{A,b},{A,1},{B,a},{B,b},{B,1},{a,1},{b,1},{A,a,1},{A,b,1},{B,a,1},{B,b,1},{C,a,1},{C,b,1}];
编辑
目前,我已执行以下代码,并且能够获得两个长度的组合。
NSArray *set1 = [NSArray arrayWithObjects:@"A",@"B",@"C", nil];
NSArray *set2 = [NSArray arrayWithObjects:@"a",@"b", nil];
NSArray *set3 = [NSArray arrayWithObjects:@"1",nil];
NSArray *allSets = [NSArray arrayWithObjects:set1,set2,set3,nil];
NSMutableArray *combinations = [NSMutableArray new];
for (int index = 0; index < allSets.count; index++) {
[combinations addObject:[NSMutableArray array]];
}
NSMutableArray *singleCombinations = combinations[0];
for (NSArray *set in allSets) {
[singleCombinations addObjectsFromArray:set];
}
for (int outerIndex = 0; outerIndex < allSets.count-1; outerIndex++) {
NSArray *set = allSets[outerIndex];
for (id object1 in set) {
for (int innerIndex = outerIndex+1; innerIndex<allSets.count; innerIndex++) {
NSArray *nextSet = allSets[innerIndex];
for (id object2 in nextSet) {
NSString *combi = [NSString stringWithFormat:@"%@%@",object1,object2];
NSLog(@"%@",combi);
}
}
}
}
任何帮助吗?
最佳答案
使用以下功能a2
的所有元素到a1
的每个元素:
NSArray *combinations(NSArray *a1, NSArray *a2)
{
NSMutableArray *result = [NSMutableArray array];
for (NSArray *elem1 in a1) {
[result addObject:elem1];
for (id elem2 in a2) {
[result addObject:[elem1 arrayByAddingObject:elem2]];
}
}
return result;
}
您可以通过从一个空数组开始迭代获得结果,然后
与您的集合相结合:
NSArray *set1 = @[@"A", @"B", @"C"];
NSArray *set2 = @[@"a", @"b"];
NSArray *set3 = @[@"1"];
NSArray *result = @[@[]];
result = combinations(result, set1);
result = combinations(result, set2);
result = combinations(result, set3);
显示结果:
for (NSArray *item in result) {
NSLog(@"{ %@ }", [item componentsJoinedByString:@", "]);
}
输出量
{}
{1}
{ 一个 }
{a,1}
{b}
{b,1}
{ 一个 }
{A,1}
{A,一个}
{A,a,1}
{A,b}
{A,b,1}
{B}
{B,1}
{B,a}
{B,a,1}
{B,b}
{B,b,1}
{ C }
{C,1}
{C,一个}
{C,a,1}
{C,b}
{C,b,1}
关于ios - 不同NSArray对象的组合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20048824/