Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Better mousetrap (getting top N values from list X)

by BrowserUk (Patriarch)
on Feb 01, 2005 at 20:47 UTC ( #427046=note: print w/replies, xml ) Need Help??


in reply to Better mousetrap (getting top N values from list X)

It will be interesting to see how this fares in a benchmark.

#! perl -slw use strict; use List::Util qw[ reduce ]; sub topN{ my( $n, $aref ) = @_; my @topN; push @topN, reduce{ $a > $b && ( !@topN || $a < $topN[ -1 ] ) ? $a : ( !@topN || $b < $topN[ -1 ] ) ? $b : $a; } @$aref for 1 .. $n; return @topN; } my @test = 1 .. 100; print join ', ', topN 5, \@test;

Examine what is said, not who speaks.
Silence betokens consent.
Love the truth but pardon error.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2022-12-02 17:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?