Last active
August 29, 2015 14:16
-
-
Save mlms13/e11bdd7163bb174962f5 to your computer and use it in GitHub Desktop.
Solve Anagrams
This file contains 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
// beautiful | |
function findAnagram(parent, child) { | |
// split the parent string into chars and iterate | |
return parent.split('').map(function (char, index, arr) { | |
// map each char in parent to an array of substrings with the same length as child.length | |
// and alphabetize the substrings for easy comparison later | |
return arr.slice(index, index + child.length).sort().join(''); | |
}).filter(function (subset) { | |
// compare the alphabetized substring to the alphabetized child | |
return subset === child.split('').sort().join(''); | |
}).length; | |
} | |
// fast | |
function findAnagram(parent, child) { | |
var all = [], | |
matches = 0, | |
len = child.length, | |
test, | |
i, j, k; | |
for (i = 0; i <= parent.length - len; i++) { | |
all.push(parent.substr(i, len)); | |
} | |
// find matches | |
for (i = 0; i < all.length; i++) { | |
test = child; | |
for (j = 0; j < len; j++) { | |
for (k = test.length - 1; k >=0; k--) { | |
if (all[i].charAt(j) === test.charAt(k)) { | |
test = test.slice(0, k) + test.slice(k + 1); | |
break; | |
} | |
} | |
} | |
if (test.length === 0) { matches++ } | |
} | |
return matches; | |
} | |
findAnagram('AdnBndAndBdaBn', 'dAn') // 4 ("Adn", "ndA", "dAn", "And") | |
findAnagram('AbrAcadAbRa', 'cAda') // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment