So I'm trying to generate a random graph with n nodes and n*4 edges by having the nodes 1, 2, 3, ..., n and the edges being an array of triples which stores endpoint of edge 1, endpoint of edge 2 and the weight of the edge:
struct edge{
int endpoint1;
int endpoint2;
int weight;
};
This is the function to generate the array of edges (of triples):
edge* generateRandomGraph(int nrOfNodes)
{
int adjMatrix[nrOfNodes+1][nrOfNodes+1] = {0};
int nrOfEdges = nrOfNodes*4 ;
edge *edges = new edge[nrOfNodes+1];
int counter = 0;
while(counter < nrOfEdges)
{
int a = 1 + rand() % nrOfNodes;
int b = 1 + rand() % nrOfNodes;
if(a != b)
if(adjMatrix[a][b] == 0)
{
adjMatrix[a][b] = 1;
adjMatrix[b][a] = 1;
edges[counter].endpoint1 = a;
edges[counter].endpoint2 = b;
edges[counter].weight = rand() % 100;
counter++;
}
}
return edges;
}
It functions properly until one point, at element edges[31] when it freezes. What could be the problem? Debugger does not specify any error, but when I try to print the values it breaks. Maybe some segmentation fault because the filling of the array is based on the rand()?
Aucun commentaire:
Enregistrer un commentaire