Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
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.

Comment on Help with finding the min and max values of an HoA
Download Code
Re: Help with finding the min and max values of an HoA
by AppleFritter (Curate) 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 (Abbot) 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?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (13)
As of 2014-12-22 17:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (126 votes), past polls