Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find maximum and minimum value in an array of integers in Perl?

Tags:

perl

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?

like image 465
Alisha Avatar asked May 22 '12 11:05

Alisha


People also ask

How do I find the maximum value in an array in Perl?

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).

How do you find the max integer in an array?

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.

How do you find maximum integers?

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.


3 Answers

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.

like image 108
ikegami Avatar answered Oct 13 '22 08:10

ikegami


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";
like image 22
jm666 Avatar answered Oct 13 '22 08:10

jm666


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";
like image 21
Hasturkun Avatar answered Oct 13 '22 07:10

Hasturkun