Skip to content

Instantly share code, notes, and snippets.

@ngopal
Created September 22, 2015 21:02
Show Gist options
  • Save ngopal/4caa0b7a66d6ea245547 to your computer and use it in GitHub Desktop.
Save ngopal/4caa0b7a66d6ea245547 to your computer and use it in GitHub Desktop.
Some functions to generate a random network. Returned objected is ready for plug-and-play use with D3 force-directed graph examples
function initializeNodes(n) {
var arr = [];
for (var i = 0; i < n; i++) {
arr.push({id:i});
}
return arr;
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
function randomUndirectedEdges(n, nodesArray) {
var links = [];
var i = 0;
while (i < n) {
var edge = [
Math.floor(getRandomArbitrary(0, nodesArray.length)),
Math.floor(getRandomArbitrary(0, nodesArray.length))];
var revEdge = [edge[1], edge[0]];
if (links.indexOf(edge) === -1) {
if (links.indexOf(revEdge) === -1) {
if (edge[0] !== edge[1]) {
var edgeObj = {"source": edge[0], "target": edge[1], "value": 1};
links.push(edgeObj);
i = i + 1;
}
}
}
}
return links;
}
function RandomNetwork(NODES_NUM,EDGES_NUM) {
var nodes = initializeNodes(NODES_NUM);
var edges = randomUndirectedEdges(EDGES_NUM, nodes);
return { "nodes" : nodes,
"links": edges };
}
@CodeRhymesLife
Copy link

This is cool and especially useful for testing! One comment:

Both of these lines will always be false because edge and revedge are pointers to new objects each time you check. You really care about the values inside the arrays, not where they are in memory -> if (links.indexOf(edge) === -1) {
if (links.indexOf(revEdge) === -1) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment