Last active
August 29, 2015 14:20
-
-
Save bvancil/fbc95e6619dbb6c39239 to your computer and use it in GitHub Desktop.
Markov Chain Fun
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title>Markov Chain Fun</title> | |
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> | |
<!--[if lt IE 9]> | |
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> | |
<![endif]--> | |
<style type="text/css"> | |
header, section, footer, aside, nav, article, figure, audio, video, canvas { display:block; } | |
</style> | |
</head> | |
<body> | |
<p>From <a href="http://blog.javascriptroom.com/2013/01/21/markov-chains/">Markov Chains: The Sad Case of Mr. Markov and What’s His Face</a></p> | |
<script type="text/javascript"> | |
var markov = { | |
memory : {}, | |
separator : '', | |
order : 2, | |
learn : function (txt) { | |
var mem = this.memory; | |
this.breakText(txt, learnPart); | |
function learnPart (key, value) { | |
if (!mem[key]) { | |
mem[key] = []; | |
} | |
mem[key].push(value); | |
return mem; | |
} | |
}, | |
ask : function (seed) { | |
if (!seed) { | |
seed = this.genInitial(); | |
} | |
return seed.concat(this.step(seed, [])).join(this.separator); | |
}, | |
step : function (state, ret) { | |
var nextAvailable = this.memory[state] || [''], | |
next = nextAvailable.random(); | |
//we don't have anywhere to go | |
if (!next) { | |
return ret; | |
} | |
ret.push(next); | |
var nextState = state.slice(1); | |
nextState.push(next); | |
return this.step(nextState, ret); | |
}, | |
breakText : function (txt, cb) { | |
var parts = txt.split(this.separator), | |
prev = this.genInitial(); | |
parts.forEach(step); | |
cb(prev, ''); | |
function step (next) { | |
cb(prev, next); | |
prev.shift(); | |
prev.push(next); | |
} | |
}, | |
genInitial : function () { | |
var ret = []; | |
for ( | |
var i = 0; | |
i < this.order; | |
ret.push(''), i++ | |
); | |
return ret; | |
} | |
}; | |
Array.prototype.random = function () { | |
return this[Math.floor(Math.random() * this.length)]; | |
}; </script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment