noMAD
noMAD

Reputation: 7844

Print combination of characters given a sequence

I was working on the recursive code to print all possible output strings for an input sequence. For simplification I am going to shorten the problem. I have a String[] array. I want to print all possible combinations of words from [0] to [N] considering only one character from a String at a time. Example: String[] a = {"abc", "def", "ghi"} I should be printing adg, adh, adi, aeg.. etc Here is my recursive code:

void printLetters(String[] list, int count, String result)
    {
        if(list == null)
            return;
        if(count > list.length-1)
        {
            System.out.println(result);
            return;
        }
        for(int i = 0; i<list[count].length(); i++)
        {
            printLetters(list, count++, result + list[count].charAt(i) + "");
        }
    }

My code is running into an infinite loop as I am getting a StackOverflowError. Can someone point out my mistake?

Upvotes: 0

Views: 322

Answers (1)

Tudor
Tudor

Reputation: 62459

The problem is that you are post-incrementing here:

printLetters(list, count++, result + list[count].charAt(i) + "");

So the recursive call occurs first, then the increment, which practically means you keep calling the method with the same value of count. Use this instead:

printLetters(list, count + 1, result + list[count].charAt(i) + "");

And are you sure you want to increment count? Because when the recursive call returns you will have count + 1 also in the "parent method", which I don't think is what you need.

Upvotes: 3

Related Questions