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?
use List::Util qw( min max ); my $min = min @numbers; my $max = max @numbers; But List::MoreUtils's minmax is more efficient when you need both the min and the max (because it does fewer comparisons).
To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.
To find the max value for the unsigned integer data type, we take 2 to the power of 16 and substract by 1, which would is 65,535 . We get the number 16 from taking the number of bytes that assigned to the unsigned short int data type (2) and multiple it by the number of bits assigned to each byte (8) and get 16.
List::Util's min
and max
are fine,
use List::Util qw( min max );
my $min = min @numbers;
my $max = max @numbers;
But List::MoreUtils's minmax
is more efficient when you need both the min and the max (because it does fewer comparisons).
use List::MoreUtils qw( minmax );
my ($min, $max) = minmax @numbers;
List::Util is part of core, but List::MoreUtils isn't.
Without modules:
#!/usr/bin/perl
use strict;
use warnings;
my @array = sort { $a <=> $b } qw(33 32 8 100);
print "min: $array[0]\n";
print "max: $array[-1]\n";
You can use List::Util
to do this easily, eg.
use List::Util qw(min max);
my @arr = (33, 32, 8, 100);
print min(@arr)," ", max(@arr), "\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With