Вопрос

i am given the size 4 for the first array. (this will vary with the test cases).

Lets say the int[] has the elements {1, 3, 3, 4}

What algorithm or formula is there to make the permutations and put them into an int[][]?

for example: permutation of the array above in to groups of 3.
a[0][] = {1, 3, 3}
a[1][] = {1, 3, 4}
a[2][] = {1, 3, 4}
a[3][] = {3, 3, 4}

also keep in mind that the size of the first array will not always be 4, but it will always be in groups of 3.

Basically i need to put the permutations of an int[] into an another int[][]

Это было полезно?

Решение

Finally I implemented permutation algorithm for any size of input array. It was interesting, here is it:

import java.util.Arrays;

public class PermutationCalculator {
    public static void main(String[] args) {
        final int[] input = {1, 3, 3, 4};
        int[][] result = new PermutationCalculator().permutation(input);

        // print result
        for (int i = 0; i < input.length; i++) {
            System.out.println(Arrays.toString(result[i]));
        }
    }

    public int[][] permutation(int[] input) {
        int[][] result = new int[input.length][]; // i-th row
        for (int i = input.length - 1; i >= 0; i--) {

            // negI starts from 0 instead of i which start from end
            int negI = input.length - i - 1;
            result[negI] = new int[input.length - 1];

            // j is row input array index, 
            // jj is column index (column length = input array -length - 1)
            for (int j = 0, jj = 0; jj < input.length; j++, jj++)
                if (jj == i) {
                    j--;  // don't need increasing in this case 
                } else {
                    result[negI][j] = input[jj];
                }
        }

        return result;
    }
}

Output is:

[1, 3, 3]
[1, 3, 4]
[1, 3, 4]
[3, 3, 4]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top