Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: How to find the N largest values in an array?

by Anonymous Monk
on Oct 04, 2001 at 04:51 UTC ( [id://116611]=note: print w/replies, xml ) Need Help??


in reply to How to find the N largest values in an array?

If any of the doesn't make sense, see sort, perlop, perldata, perlsyn.
use strict; my @list_o_num = qw( 1 22 44 55 63 2 1 2 4 54 8 7 9 2 9 ); my @sorted_list_o_num = sort { $b <=> $a } @list_o_num; my( $num_1, $num_2, $num_3 ) = @sorted_list_o_num;
This however, does not account for duplicates (9 9 7), so this approach might be better
#!/usr/bin/perl -w use strict; my @list_o_num = qw( 9 9 9 10 9 8 7 9 6 ); my %list_o_num = map { if ( exists $list_o_num{$_} ) { $list_o_num{$_}++; } else { $_ => 1; } } @list_o_num; my @true_top_3 = sort { $b <=> $a } keys %list_o_num;
None of this is tested, but it should work (short of any typos).

Note: See blakem's comment and example here for a fix to make this solution actually work.

Replies are listed 'Best First'.
Re: Answer: Find largest ordered sequence in an array
by blakem (Monsignor) on Oct 04, 2001 at 05:05 UTC
    hmm... this looks really awkward:
    my %list_o_num = map { if(exists $list_o_num{$_}) { $list_o_num{$_}++ } else { $_ => 1 } } @list_o_num;
    For one thing, you are using a hash in the same line as you declare it with my... thats bad... I think you are trying to do something like:
    my %list_o_num; $list_o_num{$_}++ for @list_o_num; my @true_top_3 = (sort { $b <=> $a } keys %list_o_num)[0..2]; print "T3: ", join(', ',@true_top_3), "\n";
    but I can't quite tell.

    I would probably write that like so:

    #!/usr/bin/perl -wT use strict; my @list_o_num = qw(9 9 9 10 9 8 7 9 6); my %seen; my @true_top_3 = (sort { $b <=> $a } grep {!$seen{$_}++} @list_o_num)[0..2]; print "T3: ", join(', ',@true_top_3), "\n";

    -Blake

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (9)
As of 2024-03-28 09:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found