Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:
Assume you have a variable number of groups. Each group has a variable number of members. Your task is to create all possible combinations of a fixed size such that no combination includes multiple members from the same group.
Ensuring that you don't get multiple member from the same group is easy - just used Algorithm::Loops NestedLoops. Getting all possible combinations of a fixed size is easy, use an iterator such as mine. The problem with this approach is that it generates duplicates.
for my $first (@group1) { for my $second (@group2) { for my $third (@group3) { for my $fourth (@group4) { # Assume fixed size = 2 # $first, $second and $third repeat here for each memb +er in @group4 # $first, $second pairings happen multiple times } } } }
Using a %seen hash won't work for two reasons. First, you will likely run out of memory given how quickly the number of possible results can grow with just a small input size. Second, generating a combination just to skip is bad for performance of a program that will already likely not finish before the heat death of the universe.
Your challenge then is to develop an algorithm that can iterate over the possible solutions without generating duplicates. Keep in mind that the following things are variable (number of groups, number of members in each group, the fixed size of each combination).
A sample to work with: group_1 = A B C group_2 = 1 2 3 4 group_3 = yellow blue green group_4 = tiny small medium large gigantic fixed_size = 2
Cheers - L~R
|
---|