Front page | perl.beginners |
Postings from February 2002
Re: finding max value
Thread Previous
From:
Chas Owens
Date:
February 13, 2002 08:09
Subject:
Re: finding max value
Message ID:
1013616535.1680.27.camel@tert.icallinc.com
On Wed, 2002-02-13 at 10:34, merlyn@stonehenge.com wrote:
> >>>>> "Frank" == Frank <frank@fysh.org> writes:
>
>
> Frank> Yeah, my bad.. I shoulda tested it:
> Frank> $max=(sort{$a<=>$b}@a)[-1];
>
> Or sort descending, probably a bit faster than a literal slice:
>
> my ($max) = sort { $b <=> $a } @input;
>
> --
> Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
> <merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
> Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
> See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!
So it should look something like this?
sub max {
my $max;
#if the array is small then sorting is faster
if (@_ < 30) {
#sort with descending values, then grab the first one
($max) = sort { $b <=> $a } @_;
} else {
#prime the pump with the first value of the array
($max) = @_;
$max < $_ ? $max = $_ : 1 for (@_);
}
return $max;
}
--
Today is Prickle-Prickle the 44th day of Chaos in the YOLD 3168
Hail Eris!
Missle Address: 33:48:3.521N 84:23:34.786W
Thread Previous