I am supposed to write a program in JavaScript to find all the anagrams within a series of words provided. e.g.:
monk, konm, nkom, bbc, cbb, dell, ledl, llde
The output should be categorised into rows:
1. monk konm, nkom; 2. bbc cbb; 3. dell ledl, llde;
I already sorted them into alphabetical order and put them into an array. i.e.:
kmno kmno bbc bbc dell dell
However I am stuck in comparing and finding the matching anagram within the array.
Any help will be greatly appreciated.
An anagram of a string is another string that contains the same characters, only the order of characters can be different.
What is an anagram? a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman. The anagram algorithm is a simple algorithm.
Here is my take:
var input = "monk, konm, bbc, cbb, dell, ledl"; var words = input.split(", "); for (var i = 0; i < words.length; i++) { var word = words[i]; var alphabetical = word.split("").sort().join(""); for (var j = 0; j < words.length; j++) { if (i === j) { continue; } var other = words[j]; if (alphabetical === other.split("").sort().join("")) { console.log(word + " - " + other + " (" + i + ", " + j + ")"); } } }
where the output would be (the word, the match and the index of both):
monk - konm (0, 1) konm - monk (1, 0) bbc - cbb (2, 3) cbb - bbc (3, 2) dell - ledl (4, 5) ledl - dell (5, 4)
To get the characters in the in alphabetical order, I used split("") ot get an array, called sort() and used join("") to get a string from the array.
Javascript objects are excellent for this purpose, since they are essentially key/value stores:
// Words to match var words = ["dell", "ledl", "abc", "cba"]; // The output object var anagrams = {}; for (var i in words) { var word = words[i]; // sort the word like you've already described var sorted = sortWord(word); // If the key already exists, we just push // the new word on the the array if (anagrams[sorted] != null) { anagrams[sorted].push(word); } // Otherwise we create an array with the word // and insert it into the object else { anagrams[sorted] = [ word ]; } } // Output result for (var sorted in anagrams) { var words = anagrams[sorted]; var sep = ","; var out = ""; for (var n in words) { out += sep + words[n]; sep = ""; } document.writeln(sorted + ": " + out + "<br />"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With