Combinations of different NSArray objects

ぃ、小莉子 提交于 2019-12-01 00:39:11

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;
}

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);

Show the result:

for (NSArray *item in result) {
    NSLog(@"{ %@ }", [item componentsJoinedByString:@", "]);
}

Output

{  }
{ 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 }

If you have a database available in you app enviromnment you could create temp tables and make cross joins between them in order to get the required combinations. Cheers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!