Largest numeric value array

  • Thread starter Monique
  • Start date
  • #1
Monique
Staff Emeritus
Science Advisor
Gold Member
4,149
64
How do you return the largest numeric value in an array, in Perl?
 

Answers and Replies

  • #2
599
1
Maybe this helps (I don't have any Perl skills, only Googling skills :smile: ).

sub max
{ my $max = pop(@_);
foreach (@_)
{ $max = $_ if $_ > $max;
}
$max;
}

http://www.codetoad.com/forum/18_23829.asp [Broken]
 
Last edited by a moderator:
  • #3
NateTG
Science Advisor
Homework Helper
2,450
6
Monique said:
How do you return the largest numeric value in an array, in Perl?
I don't think perl has a maximum function so you have to do something like
Code:
my $tmp='';
map {$tmp=$_ if ($_>$tmp and $_=~/^-?\d*.?\d*$/s and $_=~ /\d/}  @array
die("The array doesn't contain any numbers ") unless ($tmp=~ /\d/);
return $tmp;
 
  • #4
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,916
19
I always try to advise people by asking how they would do it.

If you had to find the largest number in a list of a million numbers, how would you do it?

You would probably go through it one by one, remembering the largest number you've seen.


So, that's how you should do it on the computer: you have a variable for storing the largest number you've seen, and you iterate through the array, updating this variable whenever you see a bigger number.
 
  • #5
Monique
Staff Emeritus
Science Advisor
Gold Member
4,149
64
Well, luckily I only needed to compare three values so I took the easy way out:

Code:
        if ($frame1>$frame2&&$frame3){
            $ORF=$frame1;
        } elsif ($frame2>$frame3){
            $ORF=$frame2;
        } else {
            $ORF=$frame3;
        }
I guess the way you suggest would be best for a large array, thanks :)
 
  • #6
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,916
19
$frame1>$frame2&&$frame3
I'm not familiar with Perl syntax, but don't you mean something like ($frame1>$frame2)&&($frame1>$frame3)? (In other languages, at least, the two are much different)
 
  • #7
Monique
Staff Emeritus
Science Advisor
Gold Member
4,149
64
Hey, thanks! I tested it with some numbers and you're right :blushing:
 

Related Threads on Largest numeric value array

Replies
36
Views
33K
  • Last Post
Replies
13
Views
2K
  • Last Post
Replies
22
Views
4K
Replies
1
Views
3K
  • Last Post
Replies
4
Views
13K
  • Last Post
Replies
1
Views
3K
  • Last Post
Replies
4
Views
16K
  • Last Post
Replies
6
Views
15K
  • Last Post
Replies
1
Views
6K
  • Last Post
Replies
6
Views
2K
Top