Hello ragnarokPP, and welcome to the Monastery!
tobyink has shown you how to solve the problem with recursion, as you requested. Here is a non-recursive solution using the CPAN module Set::Scalar:
#! perl
use Modern::Perl;
use Set::Scalar;
my $class_callback = sub { join(' ', sort { $a <=> $b } $_[0]->element
+s) };
Set::Scalar->as_string_callback($class_callback);
my @sets;
for (my $i = 0; <DATA>;)
{
chomp;
my $new_set = Set::Scalar->new(split /\s+/);
my $merged = 0;
for my $j (0 .. $i - 1)
{
if ($new_set->intersection($sets[$j]))
{
$sets[$j] = $sets[$j]->union($new_set);
$merged = 1;
last;
}
}
$sets[$i++] = $new_set unless $merged;
}
print '(', $_, ")\n" for @sets;
__DATA__
1 2 4
2 3 4
3 7
4 6
5 10 11 12 13
6
7 1
Output:
1:30 >perl 424_SoPW.pl
(1 2 3 4 6 7)
(5 10 11 12 13)
1:34 >
Remember, the Perl motto is TMTOWTDI (There’s More Than One Way To Do It)!
Update: The above code doesn’t merge fully on certain types of input. The following code fixes this:
#! perl
use Modern::Perl;
use Set::Scalar;
my $class_callback = sub { join(' ', sort { $a <=> $b } $_[0]->element
+s) };
Set::Scalar->as_string_callback($class_callback);
my @sets;
for (my $i = 0; <DATA>; ++$i)
{
chomp;
$sets[$i] = Set::Scalar->new(split /\s+/);
}
print "Before merging:\n";
print '(', $_, ")\n" for @sets;
print "\n";
for my $i (reverse 1 .. $#sets)
{
for my $j (0 .. $i - 1)
{
if (defined $sets[$i] &&
defined $sets[$j] &&
$sets[$i]->intersection($sets[$j]))
{
$sets[$j] = $sets[$i]->union($sets[$j]);
$sets[$i] = undef;
}
}
}
@sets = grep { defined } @sets;
print "After merging:\n";
print '(', $_, ")\n" for @sets;
__DATA__
1 2 4
7 13
3 5 6
7 8
10 11 12
1 5
Output:
11:24 >perl 424_SoPW.pl
Before merging:
(1 2 4)
(7 13)
(3 5 6)
(7 8)
(10 11 12)
(1 5)
After merging:
(1 2 3 4 5 6)
(7 8 13)
(10 11 12)
12:17 >
Hope that helps,
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
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.
|
|