Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: "Intelligent" array joining

by dragonchild (Archbishop)
on Feb 06, 2004 at 03:40 UTC ( [id://326983]=note: print w/replies, xml ) Need Help??


in reply to "Intelligent" array joining

This sounds like a directed graph. I'd recommend looking at Graph::Directed. The following worked for me:
use Graph::Directed; my @array1 = qw(dog cat rat mouse); my @array2 = qw(dog rat mouse bird); my @array3 = qw(cat rat fish mouse); my $graph = Graph::Directed->new; $graph->add_path(@array1); $graph->add_path(@array2); $graph->add_path(@array3); my @toposort = $graph->toposort; print "@toposort\n"; ------ dog cat rat fish mouse bird

------
We are the carpenters and bricklayers of the Information Age.

Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Replies are listed 'Best First'.
Re: Re: "Intelligent" array joining
by ngomong (Sexton) on Feb 06, 2004 at 16:27 UTC
    As a follow-up... I've noticed that any duplicates in a given array will mess up the topological sort. So, I just added a quick duplicate search:
    use Graph::Directed; my @array1 = qw(dog rat rat mouse); my @array2 = qw(dog rat mouse bird); my @array3 = qw(cat rat fish mouse); my @elements; push(@elements, \@array1, \@array2, \@array3); my $graph = Graph::Directed->new; for (0..$#elements) { # Check for duplicate GUIDs in this set my %seen = (); my @dup = (); foreach my $item (@{$elements[$_]}) { if ($seen{$item}++) { push(@dup, $item); } } unless ($#dup == -1) { print "Duplicate elements: @dup"; exit; } # If all's well, add to the path $graph->add_path(@{$elements[$_]}); } my @elements_ordered = $graph->toposort; print "@elements_ordered\n";
Re: Re: "Intelligent" array joining
by ngomong (Sexton) on Feb 06, 2004 at 14:37 UTC
    Hey, wow! That's precisely what I needed. Pretty straightforward, too. I just didn't know what to look for.

    Just goes to show... with Perl, if you've got a problem, somebody's already figured it out and written a module.

    On to reading more about directed graphs and topological sorting...

    Thanks!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://326983]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (2)
As of 2024-04-19 22:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found