Perumations of size N java Array

Rohit Gupta :

In c++ permutations of an array can be generated using the function next_permutation. Is there a java equivalent of such a function to generate permutations of a size N array?

I am trying to come up with an equivalent recursive implementation but am struggling to solidify my logic.

loganrussell48 :

There isn't a built-in function like this in java. You'll have to create your own, which is not that complicated. I'll provide an edit to this answer momentarily with a solution (not necessarily the best solution)

public static void printperms(int[] perm, boolean[] used, int k)
{
    if (k == perm.length) print(perm);
    for (int i=0; i<perm.length; i++) {
        if (!used[i]) {
           used[i] = true;
           perm[k] = i;
           printperms(perm, used, k+1);
           used[i] = false;
        }
    }
}

you can then create a new method, like so, to call it:

public void perms(int n){
    printperms(new int[n], new boolean[n], 0);
}

Lastly, where I have the print method, you can have the Array added to a list instead so that you can collect them all in a list, or you can just print it out. Your choice. Do with it as you please.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=378736&siteId=1