Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^3: index of the minimum element of the array

by oiskuu (Pilgrim)
on Jan 17, 2014 at 18:13 UTC ( #1070994=note: print w/ replies, xml ) Need Help??


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

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..$#_ }


Comment on Re^3: index of the minimum element of the array
Select or Download Code
Re^4: index of the minimum element of the array
by ikegami (Pope) on Jan 17, 2014 at 18:23 UTC
    You're accessing the callback's @_ when you mean to access minindex's

      I'm passing a block to reduce.

        Ikegami is right, thats not working!

        Better pass the list as a closed over array (here @x)

        DB<109> @a= map { int rand 100 } 1..10 => (96, 10, 99, 9, 43, 8, 20, 85, 42, 26) DB<110> sub minindex { my @x=@_; reduce { $x[$a] < $x[$b] ? $a : $b } 0 .. $#_ } DB<111> print minindex @a 5

        update

        or even better like ikegami now suggested as ref to avoid overhead

        DB<114> @a= map { int rand 100 } 1..10 => (22, 15, 27, 44, 70, 85, +74, 93, 96, 14) DB<115> sub minindex { my $x=\@_; reduce { $x->[$a] < $x->[$b] ? $a : $b } 0 .. $#_ } DB<116> print minindex @a 9

        Cheers Rolf

        ( addicted to the Perl Programming Language)

        Impossible. There's no such data type. You are passing a sub reference to reduce.
        reduce BLOCK LIST
        is compiled as
        &reduce(sub BLOCK, LIST)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1070994]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2014-09-21 08:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (167 votes), past polls