I have an array with values 33, 32, 8, 100.
How can I find the maximum and minimum value in this array?
Do I need to include any special libraries?<
List::Util has the "max" and "min" functions that you can use to directly find the maximum and minimum given a list of numbers. Check if you can use that. You may also sort the array and then determine the highest and lowest number
You can use map to do this without needing libraries:
my @array = (33, 32, 8, 100);
my ($max,$min)=(-1e99,1e99); # Initialize to values outside anything in your list
map {$max=$_ if ($_>$max); $min=$_ if($_<$min);} @array;
print "max=$max, min=$min\n";
Use the List::Util module, which it is recommended to get acquainted with anyway, just like List::MoreUtils
:
D:\ :: perl -MList::Util=max -lwe "print max 324, 43, 53, 3532, 43"
3532
D:\ :: perl -MList::Util=min -lwe "print min 324, 43, 53, 3532, 43"
43
You should use List::Util which has been released with the Perl distribution since v5.7.3 so probably doesn't need installing.
use strict;
use warnings;
use feature 'say';
use List::Util qw/ max min /;
my @data = (33, 32, 8, 100);
say min @data;
say max @data;
output
8
100
Ofcourse, if you want both the maxium and minimum value of a list at the same time, it is more efficient to fetch both at once; it only has to perform 3 order comparisons per 2 items of data, rather than 4. This may matter if the data sets are big enough.
List::Util
doesn't provide a minmax
function but List::MoreUtils
does.
use strict;
use warnings;
use feature qw( say );
use List::MoreUtils qw( minmax );
my ( $min, $max ) = minmax @data;
say $min;
say $max;
The provided solutions are good, but if you want to implement it yourself it's pretty straightforward:
use strict;
use warnings;
my @array = (33, 32, 8, 100);
my ($min, $max);
for (@array) {
$min = $_ if !$min || $_ < $min;
$max = $_ if !$max || $_ > $max
};
print "min: $min\n";
print "max: $max\n";