Last active
June 3, 2019 19:24
-
-
Save J3698/7831de8b5a9d034e40b86ceb0f86a7a8 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
function createChain(words) { | |
chain = {}; | |
for (const word of words) { | |
addWordToChain(chain, word); | |
} | |
return chain; | |
} | |
/* | |
* Example: Adding "beat" to the chain will | |
* update the chain with the following transitions: | |
* "" -> "be" "be" -> "a" "ea" -> "t" | |
*/ | |
function addWordToChain(chain, word) { | |
updateOccuranceInChain(chain, '', word.slice(0, 2)); | |
for (var i = 2; i < word.length; i++) { | |
prefix = word.substring(i - 2, i); | |
updateOccuranceInChain(chain, prefix, word[i]); | |
} | |
} | |
function updateOccuranceInChain(chain, prefix, occurance) { | |
addPrefixIfNew(chain, prefix); | |
addPrefixOccuranceIfNew(chain, prefix, occurance); | |
chain[prefix][occurance]++; | |
chain[prefix]['total']++; | |
} | |
function addPrefixIfNew(chain, prefix) { | |
if (chain[prefix] == undefined) { | |
chain[prefix] = {}; | |
chain[prefix]['occurances'] = []; | |
chain[prefix]['total'] = 0; | |
} | |
} | |
function addPrefixOccuranceIfNew(chain, prefix, occurance) { | |
if (chain[prefix][occurance] == undefined) { | |
chain[prefix][occurance] = 0; | |
chain[prefix]['occurances'].push(occurance); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment