Last active
July 23, 2019 22:39
-
-
Save ldd/a5ffc537869894bb25662d4d3e3fb856 to your computer and use it in GitHub Desktop.
cute ghost idea
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
////////////////// | |
// basic Trie implementation | |
////////////////// | |
function Trie() { | |
this.head = { key: '', children: {} } | |
} | |
Trie.prototype.add = function (key) { | |
var curNode = this.head | |
, newNode = null | |
, curChar = key.slice(0, 1); | |
key = key.slice(1); | |
while (typeof curNode.children[curChar] !== "undefined" && curChar.length > 0) { | |
curNode = curNode.children[curChar]; | |
curNode.wins = key.length % 2 === 1 || curNode.wins === true; | |
curChar = key.slice(0, 1); | |
key = key.slice(1); | |
} | |
while (curChar.length > 0) { | |
newNode = { key: curChar, wins: key.length % 2 === 1, children: {} }; | |
curNode.children[curChar] = newNode; | |
curNode = newNode; | |
curChar = key.slice(0, 1); | |
key = key.slice(1); | |
} | |
} | |
; | |
////////////////// | |
function ghost(dictionary = []) { | |
const myTrie = new Trie(); | |
dictionary.forEach(word => myTrie.add(word)); | |
return Object.values(myTrie.head.children).filter(({ wins }) => wins).map(({ key }) => key) | |
} | |
function simpleGhost(dictionary = []) { | |
const myTrie = {}; | |
dictionary.forEach(word => { | |
const entry = myTrie[word[0]]; | |
myTrie[word[0]] = (entry === undefined || entry === true) && word.length % 2 === 0; | |
} | |
); | |
return Object.entries(myTrie).filter(([k, wins]) => wins).map(([key]) => key) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment