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;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.