Skip to content

Instantly share code, notes, and snippets.

@jes
Created February 22, 2019 10:27
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/2b40a9ef48b2519c50f405af9a2608f6 to your computer and use it in GitHub Desktop.
Save jes/2b40a9ef48b2519c50f405af9a2608f6 to your computer and use it in GitHub Desktop.
'use strict';
class Markov {
constructor() {
this.minLength = 6;
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(seedword) {
// 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'];
if (seedword) {
let words = seedword.match(/\S+\s*/g).map(function(x) { return x.trim(); });
sentence = sentence.concat(words);
let search = sentence.slice(-2).join(' ');
if (!this.dict[search]) {
return "Can't work with " + seedword + " m9";
}
}
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 && sentence.length >= this.minLength+2)) {
sentence.shift(); sentence.shift();
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