Skip to content

Commit acabaa8

Browse files
committed
Added example to find permutation of numbers in array
1 parent f8a4f79 commit acabaa8

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.eprogrammerz.examples.algorithm.crackingCoding;
2+
3+
import org.junit.Test;
4+
5+
import java.util.ArrayList;
6+
import java.util.Arrays;
7+
import java.util.List;
8+
9+
import static org.junit.Assert.assertEquals;
10+
11+
/**
12+
* Find permutations of list of numbers
13+
*/
14+
public class Permutations {
15+
public List<List<Integer>> findPermutations(List<Integer> num) {
16+
List<List<Integer>> permutations = new ArrayList<>();
17+
findPermutations(num, new ArrayList<>(), permutations);
18+
return permutations;
19+
}
20+
21+
private void findPermutations(List<Integer> nums, List<Integer> permutation, List<List<Integer>> permutations) {
22+
if (nums.size() == 0) {
23+
permutations.add(new ArrayList<>(permutation));
24+
} else {
25+
for (int i = 0; i < nums.size(); i++) {
26+
List<Integer> remaining1 = nums.subList(0, i);
27+
List<Integer> remaining2 = nums.subList(i + 1, nums.size());
28+
permutation.add(nums.get(i));
29+
30+
List<Integer> remaining = new ArrayList<>();
31+
remaining.addAll(remaining1);
32+
remaining.addAll(remaining2);
33+
findPermutations(remaining, permutation, permutations);
34+
permutation.remove(nums.get(i));
35+
}
36+
}
37+
}
38+
39+
@Test
40+
public void testFindDenomination() {
41+
List<List<Integer>> actual = findPermutations(Arrays.asList(1, 2, 3));
42+
List<Integer> p1 = Arrays.asList(1, 2, 3);
43+
List<Integer> p2 = Arrays.asList(1, 3, 2);
44+
List<Integer> p3 = Arrays.asList(2, 1, 3);
45+
List<Integer> p4 = Arrays.asList(2, 3, 1);
46+
List<Integer> p5 = Arrays.asList(3, 1, 2);
47+
List<Integer> p6 = Arrays.asList(3, 2, 1);
48+
List<List<Integer>> expected = Arrays.asList(p1, p2, p3, p4, p5, p6);
49+
assertEquals(expected, actual);
50+
}
51+
}

0 commit comments

Comments
 (0)