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

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.

Replies are listed 'Best First'.
Re^5: index of the minimum element of the array
by LanX (Saint) on Jan 17, 2014 at 16:06 UTC
    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)