Skip to content

Instantly share code, notes, and snippets.

@Empty2k12
Created January 16, 2017 09:59
Show Gist options
  • Save Empty2k12/02c5ad9f66e5d5bf678ba4fdbc9c397e to your computer and use it in GitHub Desktop.
Save Empty2k12/02c5ad9f66e5d5bf678ba4fdbc9c397e to your computer and use it in GitHub Desktop.
Generates a number of sentences with a Markov Chain. (Sample Text: Wikipedia Bitcoin Article)
var text = "The so called Bitcoin is a cryptocurrency and a payment system invented by an unidentified programmer, or group of programmers, under the name of Satoshi Nakamoto. Bitcoin was introduced on 31 October 2008 to a cryptography mailing list, and released as open-source software in 2009. There have been various claims and speculation concerning the identity of Nakamoto, none of which are confirmed. The system is peer-to-peer and transactions take place between users directly, without an intermediary. These transactions are verified by network nodes and recorded in a public distributed ledger called the blockchain, which uses bitcoin as its unit of account. Since the system works without a central repository or single administrator, the U.S. Treasury categorizes bitcoin as a decentralized virtual currency. Bitcoin is often called the first cryptocurrency, although prior systems existed and it is more correctly described as the first decentralized digital currency. Bitcoin is the largest of its kind in terms of total market value.";
var ngrams = [];
var order = 4;
var sentences = 3;
for(var i = 0; i <= text.length - order; i++) {
var gram = text.substring(i, i + order);
if(!ngrams[gram]) {
ngrams[gram] = [];
}
ngrams[gram].push(text.charAt(i + order));
}
markovIt();
function markovIt() {
var currentGram = text.substring(0, order);
var result = currentGram;
var generatedSentences = 0;
while(generatedSentences <= sentences) {
var possibilities = ngrams[currentGram];
var next = possibilities[Math.floor(Math.random() * possibilities.length)];
result = result + next;
if(result.charAt(result.length - 1) == '.') {
generatedSentences++;
}
currentGram = result.substring(result.length - order, result.length);
}
console.log(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment