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;
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|