Skip to content

Instantly share code, notes, and snippets.

@J3698
Last active June 2, 2019 17:39
Show Gist options
  • Save J3698/790495215c73d2ef4b75b22d69e861a1 to your computer and use it in GitHub Desktop.
Save J3698/790495215c73d2ef4b75b22d69e861a1 to your computer and use it in GitHub Desktop.
function randomWord(chain, length) {
// get initial prefix
word = randomOccurance(chain, '');
for (var i = 0; i < length - 2; i++) {
lastTwoLetters = word.substr(-2);
// restart if chain hits dead end
if (chain[lastTwoLetters] == undefined) {
return randomWord(chain, length);
}
word += randomOccurance(chain, lastTwoLetters);
}
return word;
}
/*
* If an occurrence occurs 5 times after a prefix, and the prefix's total
* is 43, the occurrence has 5/43 chance of being chosen
*/
function randomOccurance(chain, prefix) {
var index = -1;
var tracker = randint(1, chain[prefix]['total']);
while (tracker >= 1) {
index += 1;
var currentOccurance = chain[prefix]['occurances'][index];
tracker -= chain[prefix][currentOccurance];
}
return chain[prefix]['occurances'][index];
}
function randint(min, max) {
return min + Math.floor((max - min) * Math.random());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment