在Perl中打印出独特的线条

时间:2011-08-30 02:57:48

标签: perl unique

我一直受到数学问题的挑战。给定十个数字(在这种情况下,数字从1到10),有六个数字的唯一组合有多少?简短的回答是210.但是,我想知道这些组合是什么。

我已将以下代码放在一起。第一个while循环可以很好地创建许多排序组合,但是,我无法打印出唯一的行组合。如何打印出这些独特的线条?

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 six 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";
}

2 个答案:

答案 0 :(得分:4)

可能还有其他的CPAN模块,但这是一种方式:

use Math::Combinatorics qw(combine);
my @comb = combine(6, 1..10);

答案 1 :(得分:3)

(这闻起来很像家庭作业问题,所以我只会给你一个暗示)

在每次迭代中,您需要将@sorted_numbers存储在某个地方,例如:

while (my @permutation = $permutor->next) {
    ...
    @sorted_numbers = sort { $a <= > $b } @numbers;
    push(@combinations, ...);
}

my @unique_combinations = uniq @combinations;
foreach (@unique_combinations) {  ... }

因此,您必须弄清楚要推送到@combinations列表的内容,以便对uniq的调用能够满足您的需求。

其他一些指示:

(1,2,3,4,5,6,7,8,9,10) may be written (1..10)

您可以使用array slice直接从@numbers计算@permutation

my @numbers = @permutation[0..5];