Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How can I get the four highest valued letters in an array?

by thanos1983 (Parson)
on Jun 01, 2017 at 13:17 UTC ( [id://1191845]=note: print w/replies, xml ) Need Help??


in reply to How can I get the four highest valued letters in an array?

Hello supriyoch_2008,

Another possible way, using Slices.

I would have the same approach as 1nickt did already. Initially create a hash from two arrays and then simply sort the values in descending order.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash; my @x = qw/d b c e a f/; my @y = qw/4 6 5 2 9 1/; @hash{@x} = @y; print Dumper \%hash; my @sorted = (sort {$hash{$b} <=> $hash{$a}} keys %hash) [0 .. 3]; print Dumper \@sorted; __END__ $ perl test.pl $VAR1 = { 'f' => '1', 'c' => '5', 'a' => '9', 'd' => '4', 'b' => '6', 'e' => '2' }; $VAR1 = [ 'a', 'b', 'c', 'd' ];

Hope this helps.

Seeking for Perl wisdom...on the process of learning...not there...yet!

Replies are listed 'Best First'.
Re^2: How can I get the four highest valued letters in an array?
by supriyoch_2008 (Monk) on Jun 01, 2017 at 14:49 UTC

    Hi thanos1983,

    Thank you for your help. The code given by you has solved my problem.

    With deep regards,

      Hello again supriyoch_2008,

      Thanks for the feedback, just to add something here. All answers of the monks are working, try them, or at least read and understand them for educations purposes.

      Also fellow monk tybalt89 just posted a nice approach Re: How can I get the four highest valued letters in an array?, using grep.

      If I was use you I would create subroutines to test all solution through Benchmark and decide the best approach based on speed. Or decide which one is easier for your to understand and maintain in future.

      Keep up the good work and happy coding. :D

      Seeking for Perl wisdom...on the process of learning...not there...yet!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-04-25 23:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found