Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: inverting hash / grouping values

by hdb (Parson)
on Sep 27, 2013 at 15:00 UTC ( #1055993=note: print w/ replies, xml ) Need Help??


in reply to inverting hash / grouping values

It can be done this way

my %ih = map { my $k = $_; $k => [ grep { $h{$_} eq $k } keys %h ] } k +eys {reverse %h};

but it must be much slower than the simple code you have shown. Using keys and reverse to get the list of the unique values of the hash and then repeatedly grep on the keys of the original hash must be rather slow.


Comment on Re: inverting hash / grouping values
Download Code
Re^2: inverting hash / grouping values
by LanX (Canon) on Sep 27, 2013 at 15:06 UTC
    Thanks, but I wasn't clear enough!

    I would like to see an elegant solution, that is w/o deeply nested constructs like map within map.

    IMHO one of the striking points of chaining simple functions is better readability compared to nested solutions.

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Next attempt:

      use strict; use warnings; use List::Util 'reduce'; use List::MoreUtils 'mesh'; use Data::Dumper; my %t = ( a => 1, b => 2, c => 1, d => 2, e => 1, f => 2, g => 3 ); my( $k, $v ) = @{ +reduce { if( $a->[0]->[-1] eq $b->[0]->[0] ) { push @{$a->[1]->[-1]}, $b->[1]->[0]->[0]; } else { push @{$a->[0]}, $b->[0]->[0]; push @{$a->[1]}, [$b->[1]->[0]->[0]]; } $a; } map { [ [$t{$_}], [[$_]] ] } sort { $t{$a} <=> $t{$b} } keys %t } +; my %i = mesh @$k, @$v; print Dumper \%i;
        Thanks, fascinating ...

        ...but maybe I was not still not clear enough! ;-)

        I'd rather prefer a solution better (readable | self documenting | maintainable) then

        DB<140> \%h => { a => 1, b => 2, c => 1, d => 2, e => 3 } DB<141> push @{ $h2{$h{$_}} }, $_ for keys %h => "" DB<142> \%h2 => { 1 => ["c", "a"], 2 => ["b", "d"], 3 => ["e"] }

        so not necessarily a complicated solution only relying on List::Util or List::MoreUtils ...

        BUT I know that you love this kind of games ... ;D

        Cheers Rolf

        ( addicted to the Perl Programming Language)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2014-07-30 12:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (231 votes), past polls