Loading collection data...
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection.
I don't think you're saving your sorted word. In any case, it is good practice to avoid clobbering the input values. Try saving your sorted word into a new variable and using that to compare.
Thanks for taking the time to explain all this in detail bkimmel, I really appreciate it. It took me awhile to understand but I finally think I got it. If you can pre-process (sort the words) then you can use the sorted word as a key in a hash and check if the words in the array are also the key in said hash.
whoops meant to reply here.
This comment is hidden because it contains spoiler information about the solution
function anagrams(word, words) {
return words.filter(function(el) {
return anagram(word, el);
});
}
function anagram(word1, word2) {
if (word1.length != word2.length) return false;
var counts, length, char1, char2;
counts = {};
length = word1.length;
for (var i=0; i < length; i++) {
char1 = word1.charAt(i);
char2 = word2.charAt(i);
counts.hasOwnProperty(char1) ? counts[char1] += 1 : counts[char1] = 1;
counts.hasOwnProperty(char2) ? counts[char2] -= 1 : counts[char2] = -1;
}
for (k in counts) if (counts[k] != 0) return false;
return true;
}
I did use the index trick to keep the anagram comparison linear. I'm not so sure there is a solution to find all the the anagram groups within an array that is better than O(n^2). Nonetheless I think I will make a kata around lunitik's suggestion and perhaps another to check for anagram solution complexity.
I wanted to write that kata initially but could not come up with my own elegant solution that is better than O(n^2). Not even sure if it can be done more efficiently.
If you want an additional challenge push for solution that doesn't use a sort.
The fastest sorting algorithm is still n log n. If the two arrays to compare are very very very large then sorting them might take a long time. There is a solution that takes linear time.