Lola
Lola

Reputation: 43

Adding Results of Recursion to An ArrayList

I'm trying to find all permutations of a word and add that to an Arraylist and return the array list. But, I believe my recursion is right but, there is a problem with adding the results to the ArrayList.This is what I have so far. The parameters I passed were "eat" and "" and what is returned is "tea" three times

public static ArrayList<String> permutations(String word, String beginning)
{
    int l = word.length();
    ArrayList<String> temp = new ArrayList<String>();

    if(l == 0)
        temp.add(beginning + word);
    else
    {
        char c = word.charAt(l-1);
        String blah = (beginning + c);
        word = word.substring(0, l-1);
        for(int i = 0; i < l; i++)
        {
            permutations(word, blah);
            temp.add(blah + word);
        }

    }
    return temp;
}

Upvotes: 0

Views: 1237

Answers (1)

jas
jas

Reputation: 10865

Probably I didn't have the right idea of your approach to find an easy fix and by the time I got things working I ended up with this. I hope it isn't too much of a departure and that it's still helpful. The output is:

[tea, tae, eta, eat, ate, aet]

import java.util.ArrayList;

public class Perm {
    public static void main(String[] args) {
        ArrayList<String> perms = new ArrayList<String>();
        permutations("tea", perms);
        System.out.println(perms);
    }

    public static ArrayList<String> permutations(String word, ArrayList<String> perms)
    {
        int l = word.length();

        // If the word has only a single character, there is only
        // one permutation -- itself. So we add it to the list and return
        if (l == 1) {
            perms.add(word);
            return perms;
        }

        // The word has more than one character.
        // For each character in the word, make it the "beginning"
        // and prepend it to all the permutations of the remaining
        // characters found by calling this method recursively

        for (int i=0; i<word.length(); ++i) {
            char beginning = word.charAt(i);

            // Create the remaining characters from everything before
            // and everything after (but not including) the beginning char
            String blah = word.substring(0,i)+word.substring(i+1);

            // Get all the permutations of the remaining characters
            // by calling recursively
            ArrayList<String> tempArray = new ArrayList<String>();
            permutations(blah, tempArray);

            // Prepend the beginning character to each permutation and
            // add to the list
            for (String s : tempArray) {
                perms.add(beginning + s);
            }
        }

        return perms;
    }
}

Upvotes: 1

Related Questions