Skip to content

Instantly share code, notes, and snippets.

@ldd
Last active July 23, 2019 22:39
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 ldd/a5ffc537869894bb25662d4d3e3fb856 to your computer and use it in GitHub Desktop.
Save ldd/a5ffc537869894bb25662d4d3e3fb856 to your computer and use it in GitHub Desktop.
cute ghost idea
//////////////////
// 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