Reputation: 139
I'm using the Graph package to create a graph with four vertices, like this:
my $graph = Graph->new;
$graph->add_edges(qw(a b c d));
I want to cycle through all possible combinations of two vertices, which I'm doing with a nested loop.
for my $i ($graph->vertices()){
for my $j ($graph->vertices()) {
(statement[s])
}
}
However, this results in many duplicates, such as for (a, b) and (b, a). To fix this, I would like to have a statement such that the second for loop only runs if $i is earlier in the list than $j. These aren't numbers, so a statement like if($i < $j)
does not work. But the program moves through the list in the same order. How do I refer to this order, or set an order and refer to it?
Edit: This might work if there is a way to compare indices of arrays in for loop. I'm not sure if this is possible, though.
Here is the full nested for-loop using the code given in the answer below.
use strict;
use warnings;
use Graph;
my $graph = Graph->new;
$graph->add_edges(qw(a b c d));
my @vertices = $graph->vertices();
for my $i (0..$#vertices) {
my $vi = $vertices[$i];
for my $j ($i+1..$#vertices) {
my $vj = $vertices[$j];
my $graph = Graph->new;
$graph->add_edges(qw(a b c d));
my @vertices = $graph->vertices();
$graph->add_edge("$i", "v");
$graph->add_edge("$j", "v");
$graph->delete_edge("$i", "$j");
print $graph, "\n";
}
}
Upvotes: 1
Views: 106
Reputation: 6573
Just read all the vertices into an array, then set up your nested loop.
my @vertices = $graph->vertices();
for my $i (0..$#vertices) {
my $vi = $vertices[$i];
for my $j ($i+1..$#vertices) {
my $vj = $vertices[$j];
...
}
}
UPDATE: User said he's getting the output below
0-v,1-v,a-b,c-d;
0-v,2-v,a-b,c-d;
0-v,3-v,a-b,c-d;
1-v,2-v,a-b,c-d;
1-v,3-v,a-b,c-d;
2-v,3-v,a-b,c-d
Upvotes: 1