Created
March 31, 2015 14:05
-
-
Save anissen/bf234d34a1ab4e75c2f6 to your computer and use it in GitHub Desktop.
Markov text generator
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
class Markov { | |
var cache :Map<String, Array<String>>; | |
var words :Array<String>; | |
public function new() { | |
words = []; | |
cache = new Map<String, Array<String>>(); | |
} | |
public function train(input :String) { | |
var new_words = input.split(' '); | |
words = words.concat(new_words); | |
for (t in triples(new_words)) { | |
if (!cache.exists(t[0] + ' ' + t[1])) | |
cache[t[0] + ' ' + t[1]] = []; | |
cache[t[0] + ' ' + t[1]].push(t[2]); | |
} | |
} | |
function triples(ws :Array<String>) { | |
return [ for (i in 0 ... ws.length - 2) [ws[i], ws[i+1], ws[i+2]] ]; | |
} | |
function get_from_cache(cur :String, next :String) { | |
var results = cache[cur + ' ' + next]; | |
if (results == null || results.length == 0) { | |
trace('Cannot find in cache: "$cur $next"'); | |
return ''; | |
} | |
return results[Math.floor(Math.random() * results.length)]; | |
} | |
public function generate(size :Int = 25) { | |
var seed = Math.floor(Math.random() * (words.length - 3)); | |
var this_word = words[seed]; | |
var next_word = words[seed+1]; | |
var gen_words = []; | |
for (i in 0 ... size) { | |
gen_words.push(this_word); | |
var temp_next_word = next_word; | |
next_word = get_from_cache(this_word, next_word); | |
this_word = temp_next_word; | |
} | |
gen_words.push(next_word); | |
return gen_words.join(' ');//.toUpperCase(); | |
} | |
} | |
class Test { | |
static function main() { | |
trace("---------"); | |
var markov = new Markov(); | |
markov.train('This is some little bitty silly story about a man and his house. The man is a small silly man with a big nose. End of the story.'); | |
trace(markov.generate()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment