Skip to content

Instantly share code, notes, and snippets.

@grant
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grant/561834963dc526495c45 to your computer and use it in GitHub Desktop.
Save grant/561834963dc526495c45 to your computer and use it in GitHub Desktop.
Markov Chain Generator
var numNodes = 20;
var roundNum = 100;
var a = [];
for (var i = 0; i < numNodes; ++i) {
var connections = [];
var sum = 0;
for (var j = 0; j < numNodes; ++j) {
var randNum = Math.random() / numNodes;
// round the num
randNum = Math.round(randNum * roundNum) / roundNum;
connections[j] = randNum;
sum += randNum;
}
// Fix the sum
connections = connections.map(function (oldNum) {
var newNum = oldNum * (1/sum);
// round the num
newNum = Math.round(newNum * roundNum) / roundNum;
return newNum;
});
sum = connections.reduce(function (p, n) {
return p + n;
});
// Fix the sum again
connections[numNodes - 1] += 1 - sum;
connections[numNodes - 1] = Math.round(connections[numNodes - 1] * roundNum) / roundNum;
a[i] = connections;
}
console.log(JSON.stringify(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment