|
| 1 | +package com.eprogrammerz.examples.algorithm.crackingCoding; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +public class MatrixPermutation { |
| 9 | + public List<int[][]> findMatrixPermutation(int[][] matrix) { |
| 10 | + int row = matrix.length; |
| 11 | + int col = matrix[0].length; |
| 12 | + List<Integer> nums = getList(matrix, row, col); |
| 13 | + |
| 14 | + ListPermutations listPermutations = new ListPermutations(); |
| 15 | + List<List<Integer>> permutations = listPermutations.findPermutations(nums); |
| 16 | + |
| 17 | + List<int[][]> matrixPermutations = new ArrayList<>(permutations.size()); |
| 18 | + for (List<Integer> permutation: permutations) { |
| 19 | + int[][] permMatrix = getMatrix(permutation, row, col); |
| 20 | + matrixPermutations.add(permMatrix); |
| 21 | + } |
| 22 | + return matrixPermutations; |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + public void testFindMatrixPermutation() { |
| 27 | + int[][] matrix = new int[][] { |
| 28 | + {1,2}, |
| 29 | + {3,4} |
| 30 | + }; |
| 31 | + List<int[][]> permutations = findMatrixPermutation(matrix); |
| 32 | + |
| 33 | + System.out.println("Permutation size: " + permutations.size()); |
| 34 | + for (int[][] perm: permutations) { |
| 35 | + printMatrix(perm); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private void printMatrix(int[][] matrix) { |
| 40 | + int row = matrix.length; |
| 41 | + int col = matrix[0].length; |
| 42 | + |
| 43 | + for (int r = 0; r < row; r++) { |
| 44 | + for (int c = 0; c < col; c++) { |
| 45 | + System.out.print(matrix[r][c] + " "); |
| 46 | + } |
| 47 | + System.out.println(); |
| 48 | + } |
| 49 | + System.out.println(); |
| 50 | + } |
| 51 | + |
| 52 | + private List<Integer> getList(int[][] matrix, int row, int col) { |
| 53 | + List<Integer> list = new ArrayList<>(row * col); |
| 54 | + for (int r = 0; r < row; r++) { |
| 55 | + for (int c = 0; c < col; c++) { |
| 56 | + list.add(matrix[r][c]); |
| 57 | + } |
| 58 | + } |
| 59 | + return list; |
| 60 | + } |
| 61 | + |
| 62 | + private int[][] getMatrix(List<Integer> list, int row, int col) { |
| 63 | + int[][] matrix = new int[row][col]; |
| 64 | + int idx = 0; |
| 65 | + for (int r = 0; r < row; r++) { |
| 66 | + for (int c = 0; c < col; c++) { |
| 67 | + matrix[r][c] = list.get(idx++); |
| 68 | + } |
| 69 | + } |
| 70 | + return matrix; |
| 71 | + } |
| 72 | +} |
0 commit comments