Last active
November 21, 2018 14:59
-
-
Save AimeeKnight/6df4c1f04f012e2094924ebfef2c7b94 to your computer and use it in GitHub Desktop.
Find all combinations in dictionary
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 reduceWord(active, rest, subsequences) { | |
if (!active && !rest) { | |
return; | |
} | |
if (!rest) { | |
subsequences.push(active); | |
} else { | |
reduceWord(active + rest[0], rest.slice(1), subsequences); | |
reduceWord(active, rest.slice(1), subsequences); | |
} | |
return subsequences; | |
} | |
function getSubWords(word) { | |
return reduceWord("", word, []); | |
} | |
function findAnagrams(dictionary, word){ | |
const anagrams = []; | |
const alphabetizeWord = alphabetize(word); | |
dictionary.forEach((entry) => { | |
if (alphabetizeWord === alphabetize(entry)) { | |
anagrams.push(entry); | |
} | |
}); | |
return anagrams; | |
} | |
function alphabetize(word) { | |
return word && word.split('').sort().join(''); | |
} | |
function findCombinationsFromDictionary(dictionary, word) { | |
const combinations = getSubWords(word); | |
const results = []; | |
combinations.forEach((permutation) => { | |
const anagrams = findAnagrams(dictionary, permutation); | |
results.push(anagrams); | |
}); | |
return results.flat(); | |
} | |
mocha.setup('bdd'); | |
const assert = chai.assert; | |
describe('findCombinationsFromDictionary', () => { | |
it('finds all combinations of a word in a given dictionary', () => { | |
const dictionary = ['act', 'tar', 'far', 'cat', 'tac', 'sat', 'hat', 'dog', 'at']; | |
const anagrams = findCombinationsFromDictionary(dictionary, 'cat'); | |
assert.deepEqual(anagrams, ["act", "cat", "tac", "at"]); | |
}); | |
it('returns an empty array if there are no combinations in a given dictionary', () => { | |
const dictionary = ['act', 'tar', 'far', 'cat', 'tac', 'sat', 'hat', 'dog', 'at']; | |
const anagrams = findCombinationsFromDictionary(dictionary, 'foo'); | |
assert.deepEqual(anagrams, []); | |
}); | |
}); | |
mocha.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment