2011-08-30 66 views
2

我一直在面臨數學問題的挑戰。給定十個數字(在這種情況下,數字從1到10),六個數字有多少個獨特的組合?簡短的答案是210.但是,我想知道這些組合是什麼。在Perl中打印出獨特的行

我把下面的代碼放在一起。第一個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

你並不需要先轉'@ permutation'成一個字符串,然後分割它再次。只需使用'@numbers = @permutation [0..5]'。對數字進行排序似乎有點奇怪......這不是整個練習尋找不同排列的重點嗎? – TLP

+0

實際上是唯一的組合。我只是有一些奇怪的做法:S,但我在學習;) – Steve

+0

另外,使用散列通常是找到獨特內容的最快捷方式: my @stuff =(1,2,3,3,「somestring」); my%unique; foreach my $ foo(@stuff){$ unique {$ foo} = 1; }打印鍵%唯一; –

回答

4

有可能就是這個其他CPAN模塊,但這裏有一個方法:

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

(這聞起來很像一門功課的問題,所以我想只給你一個提示)

在每次迭代你需要存儲@sorted_numbers一些地方,如:

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

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

所以你甲肝e找出什麼推到名單@combinations,以便撥打uniq將做你想做的。

其他一些指針:

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

您可以直接從@permutation計算@numbersarray slice

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