Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Looking for the first item in the chain

by Cristoforo (Curate)
on Aug 09, 2014 at 23:21 UTC ( [id://1096877]=note: print w/replies, xml ) Need Help??


in reply to Looking for the first item in the chain

Borrowing from Laurent_R's answer, you might want to consider using Graph::Undirected to get the connections. I also borrowed this graph example from somewhere, probably from here at Perl Monks but can't find the original in a search.
#!/usr/bin/perl use strict; use warnings; use Graph; my $g = Graph::Undirected->new; while (<DATA>) { chomp; my ($x, $y) = split /;/; $y = $x if $y eq ''; # will pass $y == 0 if that's the case $g->add_edge($x, $y); } my %pred; for my $aref ($g->connected_components) { my @items = sort {$a <=> $b} @$aref; my $first = $items[0]; for my $element (@items) { $pred{$element} = $first; } } print "$_ => $pred{$_}\n" for sort {$a <=> $b} keys %pred; __DATA__ 567;456 456;345 345;234 234;123 339;228 228;117 131; 435;324 324;213 372;
Prints:
117 => 117 123 => 123 131 => 131 213 => 213 228 => 117 234 => 123 324 => 213 339 => 117 345 => 123 372 => 372 435 => 213 456 => 123 567 => 123
Update: Changed $g->add_edge($x, $y || $x); to $g->add_edge($x, $y); and added $y = $x if $y eq ''; so to allow $y to be a possible zero.

Replies are listed 'Best First'.
Re^2: Looking for the first item in the chain
by vagabonding electron (Curate) on Aug 10, 2014 at 12:51 UTC

    Thank you very much Cristoforo for showing me this possibility, I did not know about the module. It seems that it could be useful in other tasks in this project as well, and the "chains" are built for free :) I am reading the documentation now. By the way, I noticed that Graph is not maintained anymore. Do you think it could be a problem in future?

      You're welcome - glad you found this useful. I don't know whether there will be a problem if it isn't being maintained anymore. Its such a useful module, so that surprises me.

      I am not well versed on the use of this module. All I've learned is from examples here on Perl Monks. For example, I don't know if your chains could have been constructed using a Directed graph. I've seen an example solving a problem using a directed graph but I found a solution to your problem using an undirected graph,

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (10)
As of 2024-04-18 15:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found