perl找到最大值并记录它是哪一个

时间:2012-10-05 22:27:26

标签: perl max

如果我有三个带整数的变量并想找到哪一个是最大的(不仅是最大整数),例如如果a是3,b是4而c是5,我想知道c是最大而不是给我一个5。如何实现这个或我应该使用

use List::Util

$d = max($a,$b,$c);
if($d == $a){}
elsif($d == $b){}
else{}

3 个答案:

答案 0 :(得分:1)

  • 将值存储在数组

  • 循环遍历数组中的每个INDEX(提示:使用0..#$arrayName构造)

  • 在单独的2个变量中保留$current_max_value$current_max_index

  • 当您发现值大于$current_max_value时,请将其存储在$current_max_value中并将当前索引存储在$current_max_index

  • 当循环结束时,您找到了最大元素的索引($current_max_index

答案 1 :(得分:1)

通过使用单独的变量,你几乎不可能做任何事情。假设您正在使用数组。

my @a = (3,4,5);

my $max_idx = 0;
for my $idx (1..$#a) {
   $max_idx = $idx
      if $a[$idx] > $a[$max_idx];
}

say $max_idx;
say $a[$max_idx];

答案 2 :(得分:1)

即使对于非常大的数据集,使用PDL也很容易。

#!/usr/bin/env perl

use strict;
use warnings;

use PDL;

my $pdl = pdl( 3,4,5 );
my (undef, $max, undef, $max_index) = $pdl->minmaximum;

print "Max: $max (at index $max_index)\n";