Skip to content

Instantly share code, notes, and snippets.

@jes
Last active May 2, 2018 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jes/faef5839b0c666be35354d0e220012d5 to your computer and use it in GitHub Desktop.
Save jes/faef5839b0c666be35354d0e220012d5 to your computer and use it in GitHub Desktop.
'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