Created
November 17, 2015 13:09
-
-
Save roobie/02b5118a03ec181e573a to your computer and use it in GitHub Desktop.
a markov chain
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
| (function () { | |
| 'use strict'; | |
| function State(properties) { | |
| var self = this; | |
| this.name = properties.name; | |
| this.transitions = properties.transitions; | |
| } | |
| State.prototype.validate = function () { | |
| var result = (this.transitions.reduce(function (out, next) { | |
| return out + next.probability; | |
| }, 0)) | |
| return result === 1.0 || (function () {throw Error('transitions probability must sum to 1.0');})(); | |
| }; | |
| State.prototype.tick = function () { | |
| this.validate(); | |
| var rn = Math.random(); | |
| return (function loop(result, rest, n0) { | |
| var n1, hit; | |
| if (result) { | |
| return result.target; | |
| } else if (n0 > 1) { | |
| throw Error('please correct this.validate();'); | |
| } | |
| n1 = n0 + rest[0].probability; | |
| hit = (n0 < rn && rn <= n1) ? rest[0] : null; | |
| return loop(hit, rest.slice(1), n1); | |
| })(null, this.transitions, 0); | |
| }; | |
| function Transition(properties) { | |
| this.target = properties.target; | |
| this.probability = properties.probability; | |
| } | |
| var stateA = new State({ | |
| name: 'A', | |
| transitions: [] | |
| }); | |
| var stateB = new State({ | |
| name: 'B', | |
| transitions: [] | |
| }); | |
| stateA.transitions = [ | |
| new Transition({ | |
| target: stateA, | |
| probability: 0.5 | |
| }), | |
| new Transition({ | |
| target: stateB, | |
| probability: 0.5 | |
| }) | |
| ]; | |
| stateB.transitions = [ | |
| new Transition({ | |
| target: stateB, | |
| probability: 0.5 | |
| }), | |
| new Transition({ | |
| target: stateA, | |
| probability: 0.5 | |
| }) | |
| ]; | |
| state = stateA; | |
| var list = function (elementCount) { | |
| return new Array(elementCount).join(' ').split(' '); | |
| }; | |
| list(10).forEach(function main() { | |
| var result = list(100).map(function () { | |
| return (state = state.tick()).name; | |
| }); | |
| var a = result.filter(function (t) {return t === 'A'}); | |
| var b = result.filter(function (t) {return t === 'B'}); | |
| console.log('A', a.length, 'B', b.length, result.join('')); | |
| }); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment