views:

314

answers:

2

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 i.e.: "kmno kmno bbc bbc dell dell" and put them into an array.

However I am stuck in comparing and finding the matching anagram within the array.

Any help will be greatly appreciated.

+2  A: 

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 />");
}
Emil H
Could you please elaborate your code? I am even more confused after reading this. Thanks in advance.
jiaoziren
+2  A: 

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 alphbetical = word.split("").sort().join("");

    for ( var j = 0; j < words.length; j++) {

        if(i === j){
            continue;
        }

        var other = words[j];
        if(alphbetical === other.split("").sort().join("")){
            print(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.

Note: when you want to test this in a browser, you have to remove the "print()" calls and use "alert()" or something.

Tim Büthe
Thanks buddy. It's been very helpful.
jiaoziren