Question

my idea is to create a tool which generate every possible anagram for a sequence of characters, for the sake of mathematics I will use numbers here (which I will use to indicate the indices of the chars given).

The idea is the following, the output should be as seen next to each number.

n = 1: 0

n = 2: 0; 01; 1; 10

n = 3: 0; 01; 02; 012; 021; 1; 10; 12; 102; 120; 2; 20; 21; 201; 210

(And continually move on in this trend)

I can generate the sequence in which a number occurs multiple times, but the problem with this is that this generates a lot of overhead, since the number of mistakes grows exponentially, which causes a lot of overhead, so checking if the sequence contains duplicates is no option.

Does anybody have an idea? (Below you will find the code used to generate the sequence with duplicates I used in Java)

public Set<String> generatePossibleAnagrams(String inputString) {
        char[] input = inputString.trim().toUpperCase().toCharArray();
        Arrays.sort(input);
        Set<String> anagrams = new TreeSet<String>();
        int currentLength = 1;

        while (currentLength <= input.length) {
            int[] indices = new int[currentLength];
            for (int i = 0; i < currentLength; i++) {
                indices[i] = 0;
            }

            boolean hadAllPossibilities = false;

            while (!hadAllPossibilities) {
                anagrams.add(generateCurrent(input, indices));

                indices[0]++;

                for (int i = 0; i < currentLength; i++) {
                    if (indices[i] >= input.length) {
                        indices[i] = 0;
                        if (i + 1 < currentLength) {
                            indices[i + 1]++;
                        } else {
                            hadAllPossibilities = true;
                        }
                    }
                }
            }

            currentLength++;
        }


        return Collections.unmodifiableSet(anagrams);
    }

private String generateCurrent(char[] input, int[] indices) {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < indices.length; i++) {
            builder.append(input[indices[i]]);
        }

        return builder.toString();
    }
Was it helpful?

Solution 2

I solved it myself today, the answer can be found on https://sourceforge.net/projects/anagramsolver/

OTHER TIPS

You can put the sequences in a HashMap, and then check whether that sequence exists in a HashMap or not, by the help of contains() method in HashMap. As there is BigO( N ) for searching in HashMap, so the operation is not too much costly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top