I've been challenged with a mathematics problem. Given ten numbers (in this case, numbers from 1 to 10), how many unique combinations of six numbers are there? The short answer is 210. However, I would like to know what these combinations are.
I have put the following code together. The first while loop works fine to create a lot of sorted combinations, however, I haven't been able to print out only the unique line combinations. How can I print out these unique lines?
my %hash;
my @sorted_numbers;
# make all permutations with numbers from 1 to 10
my $permutor = List::Permutor->new (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
while ( my @permutation = $permutor->next() ) {
my $string = "@permutation";
my ($N1, $N2, $N3, $N4, $N5, $N6, $N7, $N8, $N9, $N10) = split (/ /, $string);
# chose only the first 开发者_StackOverflowsix numbers and sort them in ascending order
my @numbers = ($N1, $N2, $N3, $N4, $N5, $N6);
@sorted_numbers = sort {$a <=> $b} @numbers;
}
# print out the unique number combinations from the temp file
my @unique_combinations = uniq @sorted_numbers;
foreach ( @unique_combinations ) {
print $_, "\n";
}
There are probably other CPAN modules for this, but here's one way:
use Math::Combinatorics qw(combine);
my @comb = combine(6, 1..10);
(this smells a lot like a homework problem, so I'm only going to give you a hint)
On each iteration you need to store @sorted_numbers
some place, e.g.:
while (my @permutation = $permutor->next) {
...
@sorted_numbers = sort { $a <= > $b } @numbers;
push(@combinations, ...);
}
my @unique_combinations = uniq @combinations;
foreach (@unique_combinations) { ... }
So you have to figure out what to push onto the list @combinations
so that the call to uniq
will do what you want.
Some other pointers:
(1,2,3,4,5,6,7,8,9,10) may be written (1..10)
You can compute @numbers
directly from @permutation
with an array slice:
my @numbers = @permutation[0..5];
精彩评论