Front page | perl.fwp |
Postings from March 2002
Array maximum/minimum
Thread Next
From:
Jonathan E. Paton
Date:
March 27, 2002 16:16
Subject:
Array maximum/minimum
Message ID:
20020328001620.50046.qmail@web14608.mail.yahoo.com
Dear list,
I have a little problem that I'm not sure if it can
be solved. Basically, this is a spill from the
beginners@perl.org, where it was asked:
How do I get the maximum and minimum values of an
array?
All the obvious answers were given (including sort),
but I wanted something a little most hackish.
The regular expression version I managed is:
__BEGIN PERL__
my @array = qw(3 4 1 2);
($max, $min)=("@array"=~/^([\d.]+)/, $1);
"@array"=~/(?:^|[^\d.])([\d.]+)(?=[^\d.]|$)(?{$max<$1?$max=$1:{}})$/;
"@array"=~/(?:^|[^\d.])([\d.]+)(?=[^\d.]|$)(?{$min>$1?$min=$1:{}})$/;
print "Maximum = $max\n";
print "Minimum = $min\n";
__END PERL__
Unfortunately, that requires three lines, not two
which I had hoped for. I was looking for the form:
($max)="@array"=~/regex/;
($min)="@array"=~/regex/;
but I couldn't manage it using (??{}) which I think
should be able to do it.
I wanted the regular expression engine bump along
the numbers... asserting that a number
higher/lower didn't exist further along. Return
as soon as that asssertion suceeds.
Can anyone...
1. ...make it work the way I imagine
2. ...make it work in a more/less obfuscated
way employing a minimum amount of regexs
3. ...do something completely unexpected
4. ...do something that's fun/interesting.
My attempt (broken) was:
$max = $array =~ /([\d.]+)(?=([\d.]+)(??{$1>$2?"":"_"})))/;
Enjoy, but I suspect my diversionary tactics
won't work... you'll all still manage to do
better than myself in TPR(0,2) ;-)
Jonathan Paton
PS: Apologies if this has been covered before,
either here or some other prominant Perl site/list.
__________________________________________________
Do You Yahoo!?
Everything you'll ever need on one web page
from News and Sport to Email and Music Charts
http://uk.my.yahoo.com
Thread Next
-
Array maximum/minimum
by Jonathan E. Paton