Skip to content

Instantly share code, notes, and snippets.

@AimeeKnight
Last active November 21, 2018 14:59
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 AimeeKnight/6df4c1f04f012e2094924ebfef2c7b94 to your computer and use it in GitHub Desktop.
Save AimeeKnight/6df4c1f04f012e2094924ebfef2c7b94 to your computer and use it in GitHub Desktop.
Find all combinations in dictionary
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