我一直在面臨數學問題的挑戰。給定十個數字(在這種情況下,數字從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";
}
你並不需要先轉'@ permutation'成一個字符串,然後分割它再次。只需使用'@numbers = @permutation [0..5]'。對數字進行排序似乎有點奇怪......這不是整個練習尋找不同排列的重點嗎? – TLP
實際上是唯一的組合。我只是有一些奇怪的做法:S,但我在學習;) – Steve
另外,使用散列通常是找到獨特內容的最快捷方式: my @stuff =(1,2,3,3,「somestring」); my%unique; foreach my $ foo(@stuff){$ unique {$ foo} = 1; }打印鍵%唯一; –