in reply to finding local minima/maxima for a discrete array

i found another way, a bit faster probably:
my $d1 = 0; my @min; my @max; for(0 .. $#data-1) { my $d = $data[$_+1]-$data[$_]; push @{ $d<0 ? \@max : \@min }, [$_, $data[$_]] if $d*$d1<=0 && $d!=0 $d1 = $d; } if($d1>0) {push @max, [$#data, $data[-1]];} if($d1<0) {push @min, [$#data, $data[-1]];} print "max $$_[1] at $$_[0]\n" for(sort {$b[1] <=> $a[1]} @max); print "min $$_[1] at $$_[0]\n" for(sort {$a[1] <=> $b[1]} @min);
$d*$d1 will be negative when the sign of $d and $d1 does not match, meaning that the the values passed from increasing to decreasing or vice-versa

Oha

Replies are listed 'Best First'.
Re^2: finding local minima/maxima for a discrete array
by ysth (Canon) on Aug 01, 2007 at 07:48 UTC
    You can't do the $d1 = $d when $d is 0 or you treat the transition between 2 and 3 as significant in 1 2 2 3. I think your $d * $d1 <= 0 && $d != 0 is the same (only slightly slower, not faster as you guess) as $d && $d != $d1 with $d set by <=> instead of -. With the final checks after the for loop being > and < , it's treated as neither a minimum or maximum when the whole array is equal; with >= and <= instead it's treated as both. You could argue for either way.