in reply to Re: how to find combine common elements of an array?
in thread how to find combine common elements of an array?
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:
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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: how to find combine common elements of an array?
by BrowserUk (Patriarch) on Apr 25, 2011 at 16:40 UTC | |
by wind (Priest) on Apr 26, 2011 at 02:23 UTC |