Last active
August 29, 2015 14:04
-
-
Save ngopal/d76a211bbd508f432eb2 to your computer and use it in GitHub Desktop.
Extremely simple implementation of a network graph library
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 node(inid,inname) { | |
return { | |
id : inid, | |
name : inname | |
}; | |
} | |
function edge(node1,node2) { | |
return { | |
source : node1, | |
target : node2 | |
}; | |
} | |
function binomialCoefficient(n,choose) { | |
// http://stackoverflow.com/questions/12983731/algorithm-for-calculating-binomial-coefficient | |
var r = 1; | |
var d; | |
if (choose > n) return 0; | |
for (d = 1; d <= choose; d++) | |
{ | |
r *= n--; | |
r /= d; | |
} | |
return r; | |
} | |
function graph(nods,edgs) { | |
return { | |
nodes : nods, | |
edges : edgs, | |
density : function () { | |
return 2*binomialCoefficient(n,2) / (nods.length)*(nods.length-1); | |
}, | |
size : function () { | |
return {"nodes" : nods.length, "edges" : edgs.length}; | |
}, | |
averageDegree : function() { | |
return 2*binomialCoefficient(n,2) / n; | |
} | |
}; | |
} | |
function randomGraph(numberNodes,numberEdges) { | |
var nodes = []; | |
var edges = []; | |
for (n = 0; n < numberNodes; n++) { | |
nodes.push(node(n,n.toString())); | |
} | |
for (e = 0; e < numberEdges; e++) { | |
var rand1 = Math.floor(Math.random() * (nodes.length-0)); | |
var rand2 = Math.floor(Math.random() * (nodes.length-0)); | |
if (rand1 !== rand2) { | |
edges.push(edge(nodes[rand1],nodes[rand2])); | |
} | |
} | |
return graph(nodes,edges); | |
} | |
g = randomGraph(10,12); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment