rats1234567
rats1234567

Reputation: 1

Generating a random graph with a given # of edges and nodes

I want to generate a random graph for a given number of nodes + edges. When I run it, it returns an edgelist of all zeroes (e.g. if I run it with five nodes and edges, it returns five pairs of zeroes as the edgelist). Is there something wrong with this part of the code that would be causing that?

public GraphEdgeList(int nNodes, int nEdges) {
    if (nNodes != 0){
        for (int i = 0; i < nEdges; i++){
            int u = (int) Math.random()* nNodes;
            int v = (int) Math.random()* nNodes;
            
            addEdge(u, v);
        }
    }
}

Upvotes: 0

Views: 301

Answers (1)

Ralf Kleberhoff
Ralf Kleberhoff

Reputation: 7290

It's easy to forget the exact rules on execution order, as in

int u = (int) Math.random()* nNodes;

Is it first compute Math.random()* nNodes, and then truncate the result to an integer, or is it first (int) Math.random(), and then multiply that integer it with nNodes? If you're unsure, place parentheses, then you don't have to remember the detailed rules:

int u = (int) (Math.random()* nNodes);

And, with your expression, the default execution rules first do (int) Math.random(). The random() result is a fractional value between 0 and 0.99999..., and casting it to int always gives zero. Multiply that with nNodes, and it's still zero - surely not what you had in mind.

Upvotes: 1

Related Questions