0

So I have a question that's kinda weird.

I have a list of "Word" objects. A "Word" object contains one string, myCWord which is equal to the canonical version of a String passed into the Word.

For example:

Word one = new Word("cba");

one.getMyCWord(); // returns abc

Canonical form is the sorted characters in the String.

So now I have a list of words, where I can access the canonical version of the Strings they hold.

I need an algorithm to create "sub lists" which are lists of which contain a set of words which are anagrams of eachother.

So if I have:

List<AnagramSet> aSet = new LinkedList<AnagramSet>();
List<Word> words = new LinkedList<Word>();
words.add("ok"); // cword returns ko
words.add("abc"); // cword returns abc
words.add("cba"); // cword returns abc still

someMethod(words);

someMethod(List<Word> a) {
// build new sub lists

AnagramSet.add(new Anagram(temp));

}

How can I build the sublists correctly?

Andrew
  • 995
  • 6
  • 10

2 Answers2

1

This will cycle through all the words in wordlist and if they are anagrams, they are are placed in anagrams.

boolean isAnagram(Word word){
    if(word.myCWord() == word){
        return true;
    } else {
        return false;
    }
}

void anagramAlgorithm(List<Word> wordlist){
    List<Anagram> anagrams = new LinkedList<Anagram>();
    for(Word w : worldlist){
        if(isAnagram(w)) anagrams.add(new Anagram(w));
    }
    // Is this what you want?
    aSet.add(anagrams);
}
Lux
  • 1,540
  • 1
  • 22
  • 28
0

Make a HashMap that maps canonical words to lists of words. Iterate over your words. For each word:

  • Is the canonical word a key in the map? If not, add it and associate an empty list with it.

  • Look up the list associated with the canonical word and add the actual word to it.

Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47