With the recent question, How can sets be recursively concatenated when intersecting with each other, I ended up revisiting these solutions and providing a streamlined answer. I must say that I'm definitely a fan of jaredor's solution below, but I noticed a couple areas where yours could be improved efficiency wise and one potential bug:
- Efficiency: loop $j from $i+1 to $#array instead of the entire array.
- Efficiency: using redo instead of goto so that fully reduced elements don't need to be gone over again.
- bug: dedup will potentially drop numbers that are substrings of other numbers. ie 11 and 111.
Here's my suggested changes applied to your solution:
#! perl -slw
use strict;
use Data::Dump qw[ pp ];
my @array = ("11 12","11 13", "9 8 7", "3 4", "11 4 111") ;
## combine
AGAIN: for my $i ( 0 .. $#array ) {
for my $j ( $i+1 .. $#array ) {
for my $n (split ' ', $array[ $j ]){
if( $array[ $i ] =~ m[\b$n\b] ) {
$array[ $i ] .= ' ' . splice @array, $j, 1;
redo AGAIN;
}
}
}
}
## dedup
for ( @array ) {
1 while s[(\b\d+)\s(?=.*\b\1\b)][]g;
}
pp \@array;