Beefy Boxes and Bandwidth Generously Provided by pair Networks Russ
Perl Monk, Perl Meditation
 
PerlMonks  

Re: how to find combine common elements of an array?

by jaredor (Deacon)
on Apr 06, 2011 at 05:23 UTC ( #897662=note: print w/ replies, xml ) Need Help??


in reply to how to find combine common elements of an array?

Thanks to inspiration from BrowserUK and wind (though I still have a ways to go before I grok their replies) I think I have something to share if only for terseness.

#!/usr/bin/env perl use strict; use warnings; use List::Util(qw(min)); use List::MoreUtils(qw(uniq)); my @array = map {[split]} ("11 12", "11 13", "9 8 7", "3 4", "11 4"); my %v2g = (); my %g2v = (); for my $i (@array) { my @sg = sort {$a<=>$b} uniq grep {defined} (@v2g{@$i}, min @$i); my $sg = shift @sg; $g2v{$v2g{$_} ||= $sg}->{$_}++ for @$i; for my $j (@sg) { @v2g{keys %{$g2v{$j}}} = ($sg) x keys %{$g2v{$j}}; @{$g2v{$sg}}{keys %{$g2v{$j}}} = values %{$g2v{$j}}; delete $g2v{$j}; } } print join ("\n", map {join " ", sort {$a<=>$b} keys %$_} values %g2v) +, "\n";

Output

3 4 11 12 13
7 8 9

About the only thing really new to add to the discussion is that this problem seems to be equivalent to finding the disjoint subgraphs of a vertex adjacency matrix of a non-directed graph. So there's probably an algorithm out there that puts this code's efficiency to shame.


Comment on Re: how to find combine common elements of an array?
Download Code
Re^2: how to find combine common elements of an array?
by jaredor (Deacon) on Apr 09, 2011 at 22:37 UTC

    Here's a better version. I was going to wipe my scratchpad and saw that I could do one thing better ... then another ... then realized that there didn't need to be an identified element per subgraph...

    #!/usr/bin/env perl use strict; use warnings; use List::MoreUtils(qw(uniq)); my @array = map {[split]} ("11 12", "11 13", "9 8 7", "3 4", "11 4"); my %g = (); for my $i (@array) { my @v = map {@$_} uniq map {$g{$_} or [$_]} @$i; @g{@v} = (\@v) x @v; } print join ("\n", map {join " ", sort {$a<=>$b} @$_} uniq values %g), +"\n";

    Same output as above, although now the ordering of the lines is fortuitous. (But obviously can be set, if desired, by another sort.)

    Hopefully it's a bit more clear that, since each iteration creates a complete set of associated vertices, the process finds the sets of vertices of the connected subgraphs of an arbitrary graph.

    (Please pardon the enthusiasm, this is the kind of stuff I like to think about.)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (16)
As of 2014-04-16 15:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (431 votes), past polls