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

Categories

I'm not very familiar with recursion in Java. I'm trying to write a method that calculates all the permutations of an array of integers. I need to modify the following perfectly working method so that, instead of printing to screen all the permutations of an array, it inserts them in a bidimensional array. So the input of the method is the array of n integers and the output is a bidimensional array with n! rows and n columns. The program I need to modify is this:

public static void permute(int[] array, int k)
{
    for(int i=k; i<array.length; i++)
    {
        int temp;
        temp = array[i];
        array[i] = array[k];
        array[k] = temp;
        permute(array, k+1);
        int temp2;
        temp2 = array[i];
        array[i] = array[k];
        array[k] = temp2;
    }
    if (k == array.length-1)
    {
        Array.printValues(array);
    }
}

So, what I need is something like this:

public static int[][] permute(int[] array, int k)
{
    //code here
}

Thank you.

See Question&Answers more detail:os

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

1 Answer

Stick them in a list and then get an array out of it. You could go directly with an int[][] but you do not know the first dimension value without an extra repetition.

public static int[][] permuteToArray(int[] array, int k){
    ArrayList<int[]> arrL=new ArrayList<>();
    for(int i=k; i<array.length; i++)
    {
        int temp;
        temp = array[i];
        array[i] = array[k];
        array[k] = temp;
        permute(array, k+1, arrL);
        int temp2;
        temp2 = array[i];
        array[i] = array[k];
        array[k] = temp2;
    }
    if (k == array.length-1)
    {
        arrL.add(array);
    }
    return arrL.toArray(new int[][]);
}

Change permute( to be:

public static void permute(int[] array, int k, ArrayList arrL) //raw type, I know
{
    for(int i=k; i<array.length; i++)
    {
        int temp;
        temp = array[i];
        array[i] = array[k];
        array[k] = temp;
        permute(array, k+1);
        int temp2;
        temp2 = array[i];
        array[i] = array[k];
        array[k] = temp2;
    }
    if (k == array.length-1)
    {
        arrL.add(array);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...