in reply to Re: index of the minimum element of the array
in thread index of the minimum element of the array

yeah, a sub for minindex would be good. atm i am unable to patch perl on current pc, so a busrouitine for index would be the best solution for me.
  • Comment on Re^2: index of the minimum element of the array

Replies are listed 'Best First'.
Re^3: index of the minimum element of the array
by LanX (Saint) on Jan 17, 2014 at 14:00 UTC
    What did you try?

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Tried this:
      my $j = 1; my $p = $s[1]; #values are present starting from 1st index while ($j != $n - 1) { if (($p < $s[$j+1]) || ($p == $s[$j+1])) { }else{ $p = $s[$j+1]; } $j++; }
      i guess that $p should keep the minimum value of the array, but the question is how to get its index.
        please use <code> tags!
        Tried this:
        my $j = 1; my $p = $s[1]; #values are present starting from 1st index while ($j != $n - 1) { if ( ($p < $s[$j+1]) || ($p == $s[$j+1]) ) { }else{ $p = $s[$j+1]; } $j++; }
        i guess that $p should keep the minimum value of the array, but the question is how to get its index.

        well this code is broken in too many ways...

        But to keep it short, you have to set a variable $min_idx=$j+1 in the else track.

        Let me propose something more perlish

        use strict; use warnings; use Data::Dump; my @s= map { int rand 100 } 1..10; dd \@s; my $min_idx = 0; my $idx = 0; my $min = $s[0]; for my $value (@s) { ($min,$min_idx)=($value,$idx) if $value < $min ; $idx++; } dd $min,$min_idx;

        out:

        [96, 40, 65, 98, 46, 17, 2, 60, 12, 67] (2, 6)

        Cheers Rolf

        ( addicted to the Perl Programming Language)

Re^3: index of the minimum element of the array
by oiskuu (Hermit) on Jan 17, 2014 at 18:13 UTC

    Also take a look at List::Util for some basic examples.

    use List::Util 'reduce'; sub minindex { reduce { $_[$a] < $_[$b] ? $a : $b } 0 .. $#_ }

    Update: Less succinct now when fixed:

    use List::Util 'reduce'; sub minindex { my @x=@_; reduce { $x[$a] < $x[$b] ? $a : $b } 0..$#_ }

      You're accessing the callback's @_ when you mean to access minindex's

        I'm passing a block to reduce.