No such thing as a small change PerlMonks

### find minimum in list

 on Feb 10, 2004 at 13:54 UTC Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Two related questions:
1. What is the best way to find the minimum value in a list ? (sort @_)[0] is clean, but seems wasteful. I'm surprised there doesn't seem to be a built-in MIN function. Is there a clever way with map and a?b:c or something ?
2. What is the best way to find the INDEX of the minimum value in a list ? (If there are duplicates, any of their indecies are OK).
Thanks :)

Replies are listed 'Best First'.
Re: find minimum in list
by broquaint (Abbot) on Feb 10, 2004 at 14:00 UTC
Check out List::Util which became a core module as of 5.7.3
```my \$min   = min @list;
my \$idx   = first { \$list[\$_] == \$min } 0 .. \$#list;
## or for duplicates
my(@idxs) =  grep { \$list[\$_] == \$min } 0 .. \$#list;
[download]```
HTH

_________
broquaint

Great tips, thanks!
Re: find minimum in list
by Limbic~Region (Chancellor) on Feb 10, 2004 at 14:02 UTC
Anonymous Monk,
While there is a module that has just the function you are looking for, your second question leads me to offer the "low water mark" solution.
```#!/usr/bin/perl
use strict;
use warnings;

my @list = qw(4 78 3 89 4 1000 5);

my %minimum;
for my \$index ( 0 .. \$#list ) {
@minimum{ qw(index min) } = (\$index , \$list[\$index]) if ! %minimum;
if ( \$list[\$index] < \$minimum{min} ) {
@minimum{ qw(index min) } = (\$index , \$list[\$index]);
}
}
print "The index of the smallest number is : \$minimum{index}\n";
print "The valud of the smallest number is : \$minimum{min}\n";
[download]```
Cheers - L~R
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
 Username: Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://327910]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2022-06-25 10:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My most frequent journeys are powered by:

Results (81 votes). Check out past polls.

Notices?