如何从Objective-C中的数组中获取所有可能的数字组合

时间:2012-11-30 01:21:00

标签: iphone objective-c ios xcode

  

可能重复:
  Generating permutations of NSArray elements

让我说我有

[1,2]

我想要

{1}
{2}
{1, 2}
{2, 3}

1 个答案:

答案 0 :(得分:8)

我认为你要找的东西的名字是'power set'。这听起来很有趣,所以这里有一个裂缝。我依靠this very concise article来算法。我不确定这是否有效(...实际上,我确定这是低效的)大型集合。

// answer the powerset of array: an array of all possible subarrays of the passed array
- (NSArray *)powerSet:(NSArray *)array {

    NSInteger length = array.count;
    if (length == 0) return [NSArray arrayWithObject:[NSArray array]];

    // get an object from the array and the array without that object
    id lastObject = [array lastObject];
    NSArray *arrayLessOne = [array subarrayWithRange:NSMakeRange(0,length-1)];

    // compute the powerset of the array without that object
    // recursion makes me happy
    NSArray *powerSetLessOne = [self powerSet:arrayLessOne];

    // powerset is the union of the powerSetLessOne and powerSetLessOne where
    // each element is unioned with the removed element
    NSMutableArray *powerset = [NSMutableArray arrayWithArray:powerSetLessOne];

    // add the removed object to every element of the recursive power set
    for (NSArray *lessOneElement in powerSetLessOne) {
        [powerset addObject:[lessOneElement arrayByAddingObject:lastObject]];
    }
    return [NSArray arrayWithArray:powerset];
}

如果您认为这是一个守护者,您可以将其作为数组上的类别方法并删除参数。像这样测试......

NSLog(@"empty = %@", [self powerSet:[NSArray array]]);
NSLog(@"one item = %@", [self powerSet:[NSArray arrayWithObject:@"a"]]);
NSLog(@"two items = %@", [self powerSet:[NSArray arrayWithObjects:@"a", @"b", nil]]);
NSLog(@"three items = %@", [self powerSet:[NSArray arrayWithObjects:@"a", @"b", @"c", nil]]);

我只进行了这些测试,输出效果很好。剧透警报:我的控制台上的三项测试看起来大致相同(\ n已删除):

  

三项=((),           (一个),           (b)中,           (A,B),           (C),           (A,C),           (公元前),           (A,B,C))