perl - getting index of max value of array

shwaipshwaip bluffin' with my muffin Icrontian
edited April 2007 in Internet & Media
I'm going to have an array of floats, and I need to get the index of the max value. I know I can just iterate through the array and find the largest number, and save its index, but...is there a builtin perl function that does this?

Comments

  • a2jfreaka2jfreak Houston, TX Member
    edited March 2007
    Not that I know of.

    [php]
    findMaxValueIndex(@array) {
    for ($i = 0, $index = 0, $max = 0; $i < scalar(@array); $i++) {
    if ($array[$i] > $max) {
    $max = $array[$i];
    $index = $i;
    }
    }
    return $index;
    }
    [/php]
    My Perl is very rusty so my @array usage may be wrong.
  • shwaipshwaip bluffin' with my muffin Icrontian
    edited March 2007
    roughly how i did it:

    [php]
    $ind = 0;
    $max=$array[0];
    $cnt = 0;
    for my $val (@array) {
    if ($val > $max) {
    $max = $val;
    $ind = $cnt;
    }
    $cnt++;
    }
    [/php]
  • a2jfreaka2jfreak Houston, TX Member
    edited March 2007
    There's foreach() too, and I'm not sure, but I think $_ keeps track of the current index in such a loop, but it has been quite a while since I've written any perl and since there are so many short-handed ways to do things in perl I just don't remember them all anymore (in fact, I never remembered all the different syntactical sugarings).
  • shwaipshwaip bluffin' with my muffin Icrontian
    edited April 2007
    foreach() does the same as the for syntax i have above.

    It wasn't something really complicated, so I didn't worry too much about writing my own code.
Sign In or Register to comment.