简体   繁体   中英

Generating all permutative pairs of strings iteratively in Java

I am trying to write a function, such that given n strings, it generates all n P 2 pairs of such strings. For example, if I have [ab, bc, bd] , it would generate [[ab, bc], [bc, ab], [ab, bd], [bd, ab], [bc, bd], [bd, bc]] , not necessarily in that order. I have a messy recursive function that does so,

private static void permutation(ArrayList<String> names, int pos, String[] pair, ArrayList<ArrayList<String>> out) {
        if (pos == names.size()) {
            if(!names.get(0).equals(names.get(1))){
                out.add(new ArrayList<String>(Arrays.asList(names.get(0), names.get(1))));
            }
        } else {
            for (int i = 0 ; i < pair.length ; i++) {
                names.add(pair[i]);
                permutation(names, pos+1, pair, out);
            }
        }
    }

But this generates a stackoverflow error when there are over 6 strings. Can anyone help write an iterative approach for this?

You don't need a recursive function; two nested loops will do.

Basically, loop i from 0 to n-1 to get the first element of the pair; and then loop again, loop j from 0 to n-1, where i<>j , and take the pair (i,j) . (and obviously put all such pairs in the out collection.)

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