Returns the largest group of anagrams in the input array of words, in no particular order. - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Returns the largest group of anagrams in the input array of words, in no particular order.

Demo Code


import java.awt.List;
import java.util.ArrayList;
import java.util.Comparator;

public class Main{
    public static void main(String[] argv) throws Exception{
        String[] words = new String[]{"1","abc","level",null,"java2s.com","asdf 123"};
        System.out.println(java.util.Arrays.toString(getLargestAnagramGroup(words)));
    }//from  ww w. j ava2 s .  c om
    /**
     * Returns the largest group of anagrams in the input array of words, in no
     * particular order. Returns an empty array if there are no anagrams in the
     * input array.
     * 
     * @param words
     *            -- the words to be analyzed for anagrams
     * @return the largest group of anagrams from the input words
     */
    public static String[] getLargestAnagramGroup(String[] words) {
        String[] anagrams = new String[words.length]; // create an anagram array assuming every single input word is an anagram
        String[] anagramsTemp = new String[words.length];
        String[] anagramsNew = new String[0];
        int anagramIndex = 0;
        for (int i = 0; i < words.length; i++) {
            boolean iAdded = false;
            for (int j = i + 1; j < words.length; j++) {
                if (areAnagrams(words[i], words[j])) { // if the word at [i] and [j] are anagrams
                    if (wordAlreadyAdded(words[i], anagrams) == false
                            || wordAlreadyAdded(words[j], anagrams) == false) { // and neither have already been added as an anagram
                        if (iAdded == false) {
                            anagrams[anagramIndex] = words[i];
                            anagramIndex++;
                            iAdded = true;
                        }
                        anagrams[anagramIndex] = words[j];
                        anagramIndex++;
                    }
                }

            }
            anagramsTemp = anagrams;
            anagrams = cutArray(anagrams);
            if (anagramsNew.length < anagrams.length) {
                anagramsNew = anagrams;
            }
            anagrams = new String[words.length];
            anagramIndex = 0;
            iAdded = false;
        }
        insertionSort(anagramsNew, new SortByAnagrams());
        return anagramsNew;
    }
    /**
     * Behaves the same as the previous method, but reads the list of words from
     * the input filename. It is assumed that the file contains one word per
     * line. If the file does not exist or is empty, the method returns an empty
     * array because there are no anagrams.
     * 
     * @param filename
     *            -- the file containing the list of words
     * @return the largest group of anagrams from the input words
     */
    public static String[] getLargestAnagramGroup(String filename) {
        String[] wordsFromFile = AnagramTester.readFile(filename);
        return getLargestAnagramGroup(wordsFromFile);
    }
    /**
     * Returns true if the two input strings are anagrams of each other,
     * otherwise returns false.
     * 
     * @param firstWord
     *            -- first word to be compared
     * @param secondWord
     *            -- second word to be compared
     * @return whether the two words are anagrams
     */
    public static boolean areAnagrams(String firstWord, String secondWord) {
        String firstSorted = sort(firstWord);
        String secondSorted = sort(secondWord);
        if (firstSorted.equals(secondSorted)) {
            return true;
        }
        return false;
    }
    /**
     * Determines whether a specified word has already been added to the array.
     * 
     * @param word
     *            -- the word to search for in the array
     * @param array
     *            -- the array to be searched
     * @return whether the word has already been added to the array
     */
    private static boolean wordAlreadyAdded(String word, String[] array) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null && array[i].equalsIgnoreCase(word)) {
                return true;
            }
        }
        return false;
    }
    public static String[] cutArray(String[] words) {
        ArrayList<String> list = new ArrayList<String>();
        for (String s : words) {
            if (s != null && s.length() > 0) {
                list.add(s);
            }
        }
        words = list.toArray(new String[list.size()]);
        return words;

    }
    /**
     * A generic method. Sorts the input array using an insertion sort and the
     * input Comparator object.
     * 
     * @param array
     *            -- the input array of objects to be sorted
     * @param mComparator
     *            -- the comparator to be used in the insertion sort
     */
    public static <T> void insertionSort(T[] array,
            Comparator<? super T> mComparator) {
        int i, j;
        for (i = 1; i < array.length; i++) {
            T index = array[i]; // object to be inserted
            // until the insertion point is found, shift items
            for (j = i; j > 0
                    && mComparator.compare(index, array[j - 1]) < 0; j--) {
                array[j] = array[j - 1];
            }
            array[j] = index; // insert object at the right point
        }
    }
    /**
     * Returns the sorted version of the input string. The sorting is
     * accomplished using an insertion sort.
     * 
     * @param word
     *            -- the word to be sorted
     * @return the sorted result of the word
     */
    public static String sort(String word) {
        String sortedWord = "";

        // Create a char array out of the given word's characters
        char[] tempCharArray = word.toLowerCase().toCharArray();

        // Copy char array to Character array for implementation of insertion
        // sort
        Character[] wordCharacters = new Character[tempCharArray.length];
        for (int i = 0; i < tempCharArray.length; i++) {
            wordCharacters[i] = tempCharArray[i];
        }

        // Sort characters in the word according to an insertion sort algorithm
        insertionSort(wordCharacters, new SortByCharacters());

        // Place characters back into a String from the CharArray
        for (int i = 0; i < wordCharacters.length; i++) {
            sortedWord += wordCharacters[i];
        }
        return sortedWord;
    }
}

Related Tutorials