Skip to content

Commit e427c63

Browse files
committed
Added solution to find permutations for matrix
1 parent acabaa8 commit e427c63

File tree

2 files changed

+73
-1
lines changed

2 files changed

+73
-1
lines changed

src/main/java/com/eprogrammerz/examples/algorithm/crackingCoding/Permutations.java renamed to src/main/java/com/eprogrammerz/examples/algorithm/crackingCoding/ListPermutations.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
/**
1212
* Find permutations of list of numbers
1313
*/
14-
public class Permutations {
14+
public class ListPermutations {
1515
public List<List<Integer>> findPermutations(List<Integer> num) {
1616
List<List<Integer>> permutations = new ArrayList<>();
1717
findPermutations(num, new ArrayList<>(), permutations);
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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

Comments
 (0)