Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Help with finding the min and max values of an HoA

by Anonymous Monk
on Jun 21, 2014 at 09:22 UTC ( #1090744=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
I am a bit stuck using an Hash of Arrays...
So, if I print the elements, I get something like this:
id1: 0 = 1 1 = 25 id2: 0 = 1 1 = 33 2 = 0 3 = 86 id3: 0 = 1 1 = 33 id4: 0 = 1 1 = 24 2 = 24 3 = 119 4 = 24 5 = 108 id5: 0 = 1 1 = 20 2 = 0 3 = 56 id6: 0 = 29 1 = 345

How can I find, for each id, which are the minimum and maximum values of its respective array? For example, for id4, I would like to get 1 and 119 respectively.

Replies are listed 'Best First'.
Re: Help with finding the min and max values of an HoA
by AppleFritter (Priest) on Jun 21, 2014 at 09:40 UTC
    Use List::Util:
    #!/usr/bin/perl use List::Util qw(min max); use feature qw(say); %hash = ( 'id1' => [ 1, 25 ], 'id2' => [ 1, 33, 0, 86 ], 'id3' => [ 1, 33 ], 'id4' => [ 1, 24, 24, 119, 24, 108 ], 'id5' => [ 1, 20, 0, 56 ], 'id6' => [ 29, 345 ], ); foreach (sort keys %hash) { say "$_: min=" . min(@{$hash{$_}}) . ", max=" . max(@{$hash{$_}}); }
    Output:
    id1: min=1, max=25 id2: min=0, max=86 id3: min=1, max=33 id4: min=1, max=119 id5: min=0, max=56 id6: min=29, max=345
    HTH!
Re: Help with finding the min and max values of an HoA
by AnomalousMonk (Canon) on Jun 21, 2014 at 10:23 UTC

    This does the same thing as above, but puts the results into a new hash for future use:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "use List::Util qw(min max); ;; my %hash = ( id1 => [ 1, 25, ], id2 => [ 1, 33, 0, 86, ], id3 => [ 1, 33, ], id4 => [ 1, 24, 24, 119, 24, 108, ], id5 => [ 1, 20, 0, 56, ], id6 => [ 29, 345, ], ); dd \%hash; ;; my %minmax = map { my $ar = $hash{$_}; $_ => [ min(@$ar), max(@$ar) ] } keys %hash ; dd \%minmax; " { id1 => [1, 25], id2 => [1, 33, 0, 86], id3 => [1, 33], id4 => [1, 24, 24, 119, 24, 108], id5 => [1, 20, 0, 56], id6 => [29, 345], } { id1 => [1, 25], id2 => [0, 86], id3 => [1, 33], id4 => [1, 119], id5 => [0, 56], id6 => [29, 345], }
      Thanks a lot guys!
      Much appreciated!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1090744]
Approved by Corion
Front-paged by perlfan
help
Chatterbox?
[stevieb]: 16.96 hours of runtime of a Raspberry Pi on a 12v, 7.2Ah battery :) Now to watch now long it takes to recharge the battery completely with my 18v solar cells in the sun :)
[stevieb]: my high-range estimate was 18 hours

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2017-03-26 15:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (315 votes). Check out past polls.