Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

objective c - combinations of a set with given number elements

i have tried to do that but could not figure it out ,

lets say i have a set : {1,2,3,4,5}

and i want to have the combinations of 2 elements like :

{1,2}
{1,3}
{1,4}
{1,5}
{2,3}
{2,4}
{2,5}
{3,4}
{3,5}
{4,5}

how can i implement that in objective-c?

i have checked the algorithms but i could not figure out how can i do that.. here's the main url that i have checked previously : Algorithm to return all combinations of k elements from n

if anyone could help me with that i will be really happy..

regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just a nested loop to walk over the array's elements and writing the combinations to a result array should work (this code is tested and works):

NSArray *set = [[NSArray alloc] initWithObjects:
                [NSNumber numberWithInteger:1],
                [NSNumber numberWithInteger:2],
                [NSNumber numberWithInteger:3],
                [NSNumber numberWithInteger:4],
                [NSNumber numberWithInteger:5], nil];

NSMutableArray *combinations = [[NSMutableArray alloc] init];

for (NSInteger i=0; i<[set count]; i++) {
    for(NSInteger j=i+1; j<[set count]; j++){
        NSArray *newCombination = [[NSArray alloc] initWithObjects:
                                   [set objectAtIndex:i],
                                   [set objectAtIndex:j],
                                   nil];
        [combinations addObject:newCombination];
        NSLog(@"added combination %@", newCombination);
    }
}

At the end of this nested loop, NSMutableArray combinations contains all your combinations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...