Created
September 22, 2015 21:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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) {