S.Else
S.Else

Reputation: 47

Generate all permutations of ArrayList<String> of a given length

I am trying to create an algorithm where the method takes in an ArrayList and the length of the output is specified. The job of the method is to print all possible permutations of the items os the specified arraylist. For eg, if arraylist is 1,2 and length given is 3, it should give output as 112,122,121,212

Upvotes: 1

Views: 4736

Answers (1)

Liviu Stirb
Liviu Stirb

Reputation: 6075

The resultant can be built by recursively adding all the possible characters to an existing result until you get to the wished length. You start with an empty result. The algorithm for this is pretty easy:

public static void main(String... arg) {
    int n = 2;
    int l = 3;

    List<String> a = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        a.add(Integer.toString(i+1));
    }
    perm(a, "", l);
}

private static void perm(List<String> a, String result, int l) {
    if (result.length() == l) {
        System.out.println(result);
        return;
    }
    for (int i = 0; i < a.size(); i++) {
        String nr = result + a.get(i);
        perm(a, nr,l );
    }
}

output:

111
112
121
122
211
212
221
222

Upvotes: 2

Related Questions