Last active
August 29, 2015 14:04
-
-
Save grant/561834963dc526495c45 to your computer and use it in GitHub Desktop.
Markov Chain Generator
This file contains hidden or 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
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