@pointset = (...); @final = (); # The basic premise is to pull the first point off of # the queue and try to attach any of the remaining # points in the queue to it. If one of them can be # attached, remove it as well and attach correctly. # Then, push the now-longer element onto the end of # the queue. # # If you get through the queue without attaching any # new elements to the top or bottom, then push it # onto @final, instead. Eventually, @pointset will be # empty. while (defined($node = shift(@pointset))) { for $index (0 .. $#pointset) { if ($node->[0] == $pointset[$index]->[$#{$pointset[$index]}]) { # Add to front of $node shift(@$node); # Avoid point at $node->[0] dup'd @$node = (@{$pointset[$index]}, @$node); # This splice could be used directly above, but I # am aiming for clarity in this example. splice(@pointset, $index, 1); unshift(@pointset, $node); next; # Go back to the top of the while-loop } elsif ($node->[$#$node] == $pointset[$index]->[0]) { # Add to end of $node pop(@$node); # Avoid point at $node->[0] dup'd @$node = (@$node, @{$pointset[$index]}); # Again, this splice could be used directly. splice(@pointset, $index, 1); unshift(@pointset, $node); next; # Go back to the top of the while-loop } # If we reach this point, then none of the other # segments could attach to $node, so move it out # of the way. push(@final, $node); } } print scalar(@final) . " resulting graphs\n"; print Data::Dumper::Dumper(\@final);