我想在陣列中找到最大值并列印他的索引。
我寫這個是為了列印最大值;它有效,但我不知道如何列印索引。
use feature "say";
use List::Util qw(max);
@x=qw(10 -2 -48 -5 7 34 28);
say "valore massimo: ".max @x;
uj5u.com熱心網友回復:
核心List::Util自帶一個萬能reduce的,可以用來直接計算出各種結果
use warnings;
use strict;
use feature 'say';
use List::Util qw(reduce);
my @x = qw(10 -2 -48 -5 7 34 28);
my $max_idx = reduce { $x[$a] > $x[$b] ? $a : $b } 0..$#x;
say "Maximal value of $x[$max_idx] is at index $max_idx";
可以將它包裝在一個簡單的函式中,以便為操作(max_idx或其他東西,并且可以回傳元素及其索引,可能僅在串列背景關系中)有一個清晰的名稱。串列實用程式的庫通常只是將reduce運算式打包成方便的函式。
具有上述功能的實用程式max_by來自List::UtilsBy,如Silvio Mayolo 的回答所示(但我們不必先創建索引陣列)。
挑剔,但我想提一下。問題中給出的(顯然)數字qw(10 -2 -48 -5 7 34 28)串列是字串(“單詞”)串列,因為qw 運算子構建事物。
一旦以這種方式使用它們,它們就會被視為數字,就像解釋器通常所做的那樣,一切都很好。但是,由于它們顯然是數字,所以我更喜歡這樣介紹它們
my @x = (10, -2, -48, -5, 7, 34, 28);
更多的打字,但我發現它更清楚地傳達了意圖。同樣,無論如何這對大多數(任何?)代碼都沒有影響。
uj5u.com熱心網友回復:
List::UtilsBy提供max_by, 用于根據其他一些標準(可能是另一個串列)獲得最大值。
use 5.010;
use List::UtilsBy qw/max_by/;
my @x = qw(10 -2 -48 -5 7 34 28);
my @indices = (0..@x-1);
say max_by { $x[$_] } @indices;
通常,如果您在 Perl 中進行重要的串列操作,我建議您安裝List::AllUtils,這是一個包含List::Util、List::SomeUtils和List::UtilsBy.
uj5u.com熱心網友回復:
對于這樣的小任務,您實際上并不需要使用外部庫。
use strict;
use warnings;
use feature 'say';
my @x = (10, -2, -48, -5, 7, 34, 28);
my $max = 0; # first index is the max
for (0 .. $#x) {
if ($x[$_] > $x[$max]) {
$max = $_;
}
}
say "@x";
say "Max number is $x[$max] with index $max";
輸出:
10 -2 -48 -5 7 34 28
Max number is 34 with index 5
只需遍歷索引,檢查值并保存具有最高編號的索引。
uj5u.com熱心網友回復:
你正在做的任務對于編程來說絕對是基本和關鍵的。如果你開始學習編程,你應該能夠自己想出一個解決方案。
是的,有一些很好的模塊可以讓這個任務更加優雅,但是如果你正在學習編程,你至少應該自己想出一個這樣的解決方案!
printf "%d\n", max_index(10,3,22,5,4,11,33); # prints 6
printf "%s\n", max_index(34,21,100,12,9); # prints 2
sub max_index {
my ( @list ) = @_;
my $max_index = 0;
my $max_value = shift @list;
my $idx = 0;
for my $current ( @list ) {
$idx ;
if ( $current > $max_value ) {
$max_index = $idx;
$max_value = $current;
}
}
return $max_index;
}
家庭作業:
- 如果你不向函式傳遞任何元素會發生什么?應該退回什么?
- 使其與陣列參考一起使用。
- 使用經典的 for 回圈
for (..., ..., ...) { ... },不要使用shift. - 如果您將字串而不是數字傳遞給它會發生什么?
- 你知道問題4的解決方案嗎?
uj5u.com熱心網友回復:
在這種情況下,如果您希望僅使用 Perl,因為 Perl 模塊安裝受到限制 - 要在陣列中查找最大值索引,您可以使用以下演算法:
- 假設陣列中的第一個元素具有
$max值 - 將以下陣列元素與
$max - 如果滿足條件,則存盤最大元素的索引和值
use strict;
use warnings;
use feature 'say';
my @arr = qw(10 -2 -48 -5 7 34 28);
my($ind,$max) = find_max(\@arr);
say "arr[$ind] = $max";
sub find_max {
my $arr = shift;
my($i,$max)=(0,$arr->[0]);
for( 1..$#{$arr} ) {
($i,$max) = ($_,$arr->[$_]) if $max < $arr->[$_];
}
return ($i,$max);
}
輸出
arr[5] = 34
uj5u.com熱心網友回復:
你可以試試下面的代碼
use List::Util qw(max);
my @x = qw(10 -2 -48 -5 7 34 28);
my ($index) = ( grep { $x[$_] eq max(@x) } 0..$#x );
print "max ", max(@x), " index $index\n";
輸出
max 34 index 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/506251.html
