combinations of a set with given number elements

前端 未结 2 1273
南旧
南旧 2020-12-09 23:52

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 lik

相关标签:
2条回答
  • 2020-12-10 00:49

    You can accomplish this using 2 for-loops. In the first loop, you iterate through the elements as i and in the second loop from the value j=i+1 to the end of the count of the number of elements in the set.

    It could be something like this:

     for (i = 0; i < length_set; i++)
    {
        for (j = i + 1;length_set; j++)
        {
            print ("%d%d\n", set[i], set[j]);
        }
    }
    

    }

    NOTE: Its just a pseudocode and i have not checked for syntax, It is just to show the logic.

    0 讨论(0)
  • 2020-12-10 00:51

    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.

    0 讨论(0)
提交回复
热议问题