Okay, imagine my nodes as routes.
So if you want to go from level 1 to level 3, you have to pass through 1 level 2 node.
the ending node can be single, or there can be multiple nodes.
Imagine, all nodes are bus stops, and the paths are buses. A bus as to stop at all nodes it passes through.
So when going from level 1 to level 5, it has to pass through 1 node of each intermediate level.
All I want to do is
1. Create a random graph with 1 starting node, and 4-5 levels, with number of points at each level random. Last level can have one or many nodes, no issues here.
2. Print all possible Paths from A to the end nodes
So its more like a tree where you cannot go from the first level to an intermediate level by skipping the levels between the two.
| [reply] |
A quick solution to your issue (with a complexity of O((n*m)^2) (n being the number of levels and m the maximum nodes per level):
- as a structure for your nodes, simply have a hash with the name of the node-level (A, B, ...) and the numbers of nodes on that level
- As an algorithm, try the following
- traverse through each level
- generate all possible node-names of that level
- take all paths you already found and add the new node-names to each of them
The code below solves your issue. It is however just a short hack and in no way optimized. But it hopefully gives you an idea.
HTH, Rata
use strict;
use warnings;
my %nodes = ( A => 2, B => 4, C => 5, D => 1);
my @path = ("");
my @newpath;
foreach my $k (sort (keys(%nodes))) # each level
{
my @nodename;
for (my $i = 1; $i <= $nodes{$k}; $i++)
{
push (@nodename, "$k$i"); # generate
+ node-names for each level
}
foreach my $old (@path) # take all
+old paths
{
foreach my $new (@nodename) # appen
+d new node to each
{
push (@newpath, "$old-$new");
}
}
@path = @newpath; # save
+old paths
@newpath = (); # clear lis
+t of new paths
}
print join("\n", @path); # print all paths (each in a new line)
exit 0;
| [reply] [d/l] |
Thanks,this works really well, i will be building my code on this code.The enhancement I am doing is also print a list of all the nodes, and the paths passing through the nodes.
for example node B2 may have paths 2,4,6,8,9 passing thorough it. Path number is the element number of @path+1.
| [reply] |
| [reply] |