简体   繁体   中英

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

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

try the solutions given here(including the ones in the comment section)

http://www.geeksforgeeks.org/print-all-combinations-of-given-length/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM