Monthly Archives: February 2009

Anagrams

The code below is from an interesting problem I was solving as part of practice for an upcoming programming competition. It’s purpose is to read in a series of strings from an input file (the number of which is defined on the first line of that file) and discover the various permutations of the letters in the given string. This code is not intended to be elegant; It’s only an algorithm test.

import java.io.*;
import java.util.*;

public class Anagrams
{

    public static void main(String[] args) throws Exception
    {
        ArrayList answers = null;

        Scanner fin = new Scanner(new File("src/input.txt"));

        int numberOfWords = fin.nextInt();
        fin.nextLine();

        for(int i = 0; i < numberOfWords; i++)
        {

            String toPass = fin.nextLine();
            answers = findAnagrams(toPass);
        }

        for(int p = 0; p < answers.size(); p++)
            System.out.println(answers.get(p));

    }

    public static ArrayList findAnagrams(String inputString)
    {
        ArrayList answers = new ArrayList();

        char[] inputStringCharArray = inputString.toCharArray();
        int len = inputStringCharArray.length;

        for(int shift = 0; shift < inputString.length(); shift++)
        {
            answers.add(new String(inputStringCharArray));
            for(int swapPos = 1; swapPos < inputString.length(); swapPos++)
            {
                String potentialAnswer = stringFromSwap(inputStringCharArray, len-swapPos, len-swapPos-1);
                if(answers.contains(potentialAnswer) == false)
                    answers.add(potentialAnswer);
            }

            //shift inputStringCharArray around left by 1 char
            char startChar = inputStringCharArray[0];
            for(int curPos = 0; curPos < len-1; curPos++)
            {
                inputStringCharArray[curPos] = inputStringCharArray[curPos+1];
            }
            inputStringCharArray[len-1] = startChar;

        }
        return answers;
    }

    public static String stringFromSwap(char[] inputStringCharArray, int lSpot, int rSpot)
    {
        char[] passedByValue = inputStringCharArray.clone();

        char temp = passedByValue[rSpot];
        passedByValue[rSpot] = passedByValue[lSpot];
        passedByValue[lSpot] = temp;

        String toReturn = new String(passedByValue);
        return toReturn;

    }
}