Last active
May 2, 2018 13:53
-
-
Save jes/faef5839b0c666be35354d0e220012d5 to your computer and use it in GitHub Desktop.
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
| 'use strict'; | |
| class Markov { | |
| constructor() { | |
| this.maxLength = 30; | |
| this.dict = {}; | |
| } | |
| addSentence(text) { | |
| // '\0' is a sentinel marking the beginning + end of sentences | |
| text = "\0 \0 " + text + " \0"; | |
| let words = text.match(/\S+\s*/g).map(function(x) { return x.trim(); }); | |
| for (let i = 2; i < text.length; i++) { | |
| let k = words[i-2] + ' ' + words[i-1]; | |
| if (!this.dict[k]) | |
| this.dict[k] = []; | |
| this.dict[k].push(words[i]); | |
| } | |
| } | |
| getRandomValue(key) { | |
| if (!this.dict[key]) { | |
| console.log("error: encountered a state we can't proceed from: " + key); | |
| return '\0'; | |
| } | |
| return this.dict[key][Math.floor(Math.random() * this.dict[key].length)]; | |
| } | |
| generateSentence() { | |
| // try up to 100 times to generate a sentence that is less than maxLength | |
| for (let i = 0; i < 100; i++) { | |
| let sentence = ['\0', '\0']; | |
| while (1) { | |
| let search = sentence.slice(-2).join(' '); | |
| let found = this.getRandomValue(search); | |
| if (found == '\0') | |
| break; | |
| sentence.push(found); | |
| if (sentence.length > this.maxLength+2) { | |
| sentence.pop(); | |
| break; | |
| } | |
| } | |
| if (i == 99 || sentence.length < this.maxLength+2) | |
| return sentence.join(' '); | |
| } | |
| } | |
| generate(sentenceCount) { | |
| let sentences = []; | |
| while (sentenceCount--) { | |
| sentences.push(this.generateSentence()); | |
| } | |
| return sentences.join(' '); | |
| } | |
| } | |
| module.exports = Markov; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment