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

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

by wind (Priest)
on Apr 05, 2011 at 01:09 UTC ( [id://897427]=note: print w/replies, xml ) Need Help??


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

Basically you're trying to merge all sets with related values.

Well, the below logic isn't pretty, but it works. Not sure what the problem was with your code

#!/usr/bin/perl -w use strict; use warnings; my @array = map {[split / /]} ( "11 12", "11 13", "9 8 7", "3 4", "11 4" ); my %index = (); for my $i (0..$#array) { for my $val (@{$array[$i]}) { push @{$index{$val}}, $i; } } for my $i (0..$#array) { my $arr = $array[$i] or next; $array[$i] = undef; my %values = (); for my $val (@$arr) { next if $values{$val}++; for my $ind (@{$index{$val}}) { my $related = $array[$ind] or next; $array[$ind] = undef; push @$arr, @$related; } } print join(' ', sort {$a <=> $b} keys %values), "\n"; }
Outputs
3 4 11 12 13 7 8 9

Replies are listed 'Best First'.
Re^2: how to find combine common elements of an array?
by wind (Priest) on Apr 26, 2011 at 02:13 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (9)
As of 2024-04-19 08:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found