不同NSArray对象的组合 [英] Combinations of different NSArray objects
本文介绍了不同NSArray对象的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在不同的数组
中找到元素
的组合。假设我有三个 NSArray
对象为:
I want to find the combinations of the elements
in diffrent arrays
. Let say I've three NSArray
objects as:
NSArray *set1 = [NSArray arrayWithObjects:@"A",@"B",@"C", nil];
NSArray *set2 = [NSArray arrayWithObjects:@"a",@"b", nil];
NSArray *set3 = [NSArray arrayWithObjects:@"1",nil];
现在所需的答案是在数组之后
Now the required answers is following arrays
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}];
编辑
目前我已经完成了以下代码,我能够得到两个长度的组合。
Edit Currently I've did the following code and I'm able to get combinations of two length.
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
的每个元素:
Using the following function, which appends
all elements of a2
to each element of 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;
}
你可以通过以空数组和$ b $开始迭代获得结果b将它与你的套装相结合:
you can get the result iteratively by starting with an empty array and combining that with your sets:
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 }
{ a, 1 }
{ b }
{ b, 1 }
{ A }
{ A, 1 }
{ A, 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, a }
{ C, a, 1 }
{ C, b }
{ C, b, 1 }
这篇关于不同NSArray对象的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文