Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

java - Get ArrayList of all possible permutations of an ArrayList

I am trying to get all possible permutations of an ArrayList that are the same length as the input arrayList. I.e. an ArrayList of 1,2,3 would result in 123, 132, 213, 231, 321, 312, not including the shorter permutations like 1, 2, 12, 13... etc. Here is the code I have so far:

public void getAllPermutations(ArrayList<coordinate> coords) {
        ArrayList<coordinate> sub = new ArrayList<coordinate>();
        permutateSub(sub, coords);
    }

    private ArrayList<ArrayList<coordinate>> permutateSub(ArrayList<coordinate> sub,
            ArrayList<coordinate> coords) {
        int n = coords.size();
        if(n == 0) System.out.println(sub);
        else {
            if(sub.size()==n) {
            System.out.println(sub);
            for(int i = 0; i<n; i++) {
                ArrayList<coordinate> a = new ArrayList<coordinate>(sub);
                a.add(coords.get(i));
                ArrayList<coordinate> b = new ArrayList<coordinate>(coords);
                b.remove(i);
                permutateSub(a, b);
            }
        }

    }

A coordinate is a class that just has x, y, and visited to hold 2D points for a project.

Currently I am using this code to print it to the console, but I would also appreciate it if someone could shed some light into how I would store this into an ArrayList>. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Take a look at Guava's Collections2 permutations method.

Example (source)

public void permutations () {
    List<Integer> vals = Ints.asList(new int[] {1, 2, 3});

    Collection<List<Integer>> orderPerm = Collections2.permutations(vals);

    for (List<Integer> val : orderPerm) {
        logger.info(val);
    }
}

/* output:
 [1, 2, 3]
 [1, 3, 2]
 [3, 1, 2]
 [3, 2, 1]
 [2, 3, 1]
 [2, 1, 3]
*/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...