Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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

by supriyoch_2008 (Monk)
on Jun 01, 2017 at 11:22 UTC ( [id://1191833]=perlquestion: print w/replies, xml ) Need Help??

supriyoch_2008 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perlmonks,

I am interested to place the four highest valued letters in an array in descending order from two arrays x and y. Array x represents the letters and array y corresponds to the respective numerical value of each element of x. For example, 'a' refers to 9 and 'b' to 6 and so on. I have written a script which finds out the letters in descending order i.e. a b c d for the corresponding values 9 6 5 4. But I have failed to place the letters in an array. I look forward to the suggestions of perlmonks to sort out this problem.

Here goes my script:

#!/usr/bin/perl use warnings; use strict; my @x=qw/d b c e a f/; my @y=qw/4 6 5 2 9 1/; my @sorted_idx=sort{$y[$a]<=>$y[$b]}0..$#y; print "\n #################################### 4 highest valued letters: ####################################\n"; descending_order (reverse @sorted_idx[$#sorted_idx-3..$#sorted_idx]); sub descending_order {my @indices=@_; print " $x[$_] " for @indices; } exit;

I have got the results in cmd as follows:

C:\Users\S>cd d*

C:\Users\S\Desktop>y3.pl

####################################

4 highest valued letters:

####################################

a b c d

C:\Users\S\Desktop>

Expected Results:

I want the results in an array so that I can

further operate on the array elements:

my @array=qw/a b c d/; # in descending order of values

print "\n @array\n";

Result: a b c d

Replies are listed 'Best First'.
Re: How can I get the four highest valued letters in an array?
by 1nickt (Canon) on Jun 01, 2017 at 11:57 UTC

    You could use zip from List::MoreUtils to mesh the arrays into a hash, then sort the keys by the values:

    use strict; use warnings; use feature 'say'; use Data::Dumper; use List::MoreUtils 'zip'; my @x = qw/d b c e a f/; my @y = qw/4 6 5 2 9 1/; my %h = zip @x, @y; my @z = ( sort { $h{ $b } <=> $h{ $a } } keys %h )[0..3]; say Dumper \@z; __END__
    Output:
    $VAR1 = [ 'a', 'b', 'c', 'd' ];

    Hope this helps!


    The way forward always starts with a minimal test.

      Hi 1nickt,

      Thank you for your prompt reply. The code works nicely and my problem is solved.

      With kind regards,

Re: How can I get the four highest valued letters in an array?
by thanos1983 (Parson) on Jun 01, 2017 at 13:17 UTC

    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!

      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!
Re: How can I get the four highest valued letters in an array?
by tybalt89 (Monsignor) on Jun 01, 2017 at 16:02 UTC

    And now for something completely different...

    #!/usr/bin/perl # http://perlmonks.org/?node_id=1191833 use strict; use warnings; my @x=qw/d b c e a f/; my @y=qw/4 6 5 2 9 1/; my @answer; @answer[@y] = @x; @answer = (grep defined, reverse @answer)[0..3]; print "@answer\n";
Re: How can I get the four highest valued letters in an array?
by Corion (Patriarch) on Jun 01, 2017 at 11:26 UTC

    In descending_order, you print your values.

    Maybe you want to just return the values there instead to further operate on them?

      Hi Corion,

      Thank you for your comment.

      With regards,

Re: How can I get the four highest valued letters in an array?
by Discipulus (Canon) on Jun 01, 2017 at 11:43 UTC
    Hello, you can also use the very same array and cut it assigning to $#array_name special variable.

    I dont know if is or not considered a best practice but it works..

    A semplified example will show you what I mean

    perl -e "@orig=qw(A p B e C r D l);@orig=sort{ord($a)<=>ord($b)}@orig; +$#orig=3;print join ' ',@orig" A B C D

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

      Hi Discipulus,

      Thank you for your suggestions.

      With regards,

Re: How can I get the four highest valued letters in an array?
by Anonymous Monk on Jun 02, 2017 at 10:19 UTC

    To keep it simple:

    @letters = ("d","b","c","e","a","f"); @getallen = (4,6,5,2,9,1); $teller = 0; foreach $letter(@letters){ $hash{$letter}=$getallen[$teller]; $teller++; } @keyz = keys(%hash); @sorted= reverse sort(@keyz); @highest = @sorted[0..3]; foreach(@highest){ print "$_:"; print $hash{$_}; print "\n";}

      Simply garbage.


      The way forward always starts with a minimal test.

        May be

A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1191833]
Approved by 1nickt
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-19 15:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found