Coding Ninjas Logo

Home > DS Questions > I have a MXN array and want to return all possible combinations of M size.

I have a MXN array and want to return all possible combinations of M size. Let me give you an example, there's a 3X3 array. The result should be 27 combinations.



Answer:

                        
import java.util.Arrays;

public class Matrix  {
    private static int counter = 0;

    private static void combin2(int depth, int[][]matrix, int[] output)
    {
        int[] row = matrix[depth];

        if(depth == 0) {
            counter = 0;
            output = new int[matrix.length];
            System.out.println("matrix length: " + matrix.length);
        }

        for(int i=0; i < row.length; i++) {
            output[depth] = row[i];

            if(depth == (matrix.length-1)) {
                //print the combination
                System.out.println(Arrays.toString(output));
                counter++;
            } else {
                //recursively generate the combination
                combin2(depth+1, matrix, output);
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}};
        combin2(0, matrix, null);
        System.out.println("counter = " + counter);
        System.out.println("");

        matrix = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        combin2(0, matrix, null);
        System.out.println("counter = " + counter);
        System.out.println("");

        matrix = new int[][]{{1, 2, 3}, {4,5,6}, {7,8,9}, {10,11,12}};
        combin2(0, matrix, null);
        System.out.println("counter = " + counter);
        System.out.println("");
    }
}
                                            
                    


Similar Questions