Skip to content

Commit a7e76c5

Browse files
authored
feat: Backtracking algorithms (All combinations) #3912 (#3917)
* ArrayCombination function which uses Combination.java by creating an array of 1 to n * modified tests
1 parent b6563cf commit a7e76c5

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.thealgorithms.backtracking;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Finds all permutations of 1...n of length k
7+
* @author TheClerici (https://github.com/TheClerici)
8+
*/
9+
public class ArrayCombination {
10+
private static int length;
11+
12+
/**
13+
* Find all combinations of 1..n by creating an array and using backtracking in Combination.java
14+
* @param n max value of the array.
15+
* @param k length of combination
16+
* @return a list of all combinations of length k. If k == 0, return null.
17+
*/
18+
public static List<TreeSet<Integer>> combination(int n, int k) {
19+
if (n <= 0) {
20+
return null;
21+
}
22+
length = k;
23+
Integer[] arr = new Integer[n];
24+
for (int i = 1; i <= n; i++) {
25+
arr[i-1] = i;
26+
}
27+
return Combination.combination(arr, length);
28+
}
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.thealgorithms.backtracking;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import java.util.List;
6+
import java.util.TreeSet;
7+
import org.junit.jupiter.api.Test;
8+
9+
public class ArrayCombinationTest {
10+
11+
@Test
12+
void testNBeingZeroOrLess() {
13+
List<TreeSet<Integer>> zeroResult = ArrayCombination.combination(0, 1);
14+
List<TreeSet<Integer>> negativeResult = ArrayCombination.combination(-1, 1);
15+
assertNull(zeroResult);
16+
assertNull(negativeResult);
17+
}
18+
19+
@Test
20+
void testNoLengthElement() {
21+
List<TreeSet<Integer>> result = ArrayCombination.combination(2, 0);
22+
assertNull(result);
23+
}
24+
25+
@Test
26+
void testLengthOne() {
27+
List<TreeSet<Integer>> result = ArrayCombination.combination(2, 1);
28+
assert result != null;
29+
assertEquals(1, result.get(0).iterator().next());
30+
assertEquals(2, result.get(1).iterator().next());
31+
}
32+
33+
@Test
34+
void testLengthTwo() {
35+
List<TreeSet<Integer>> result = ArrayCombination.combination(2, 2);
36+
assert result != null;
37+
Integer[] arr = result.get(0).toArray(new Integer[2]);
38+
assertEquals(1, arr[0]);
39+
assertEquals(2, arr[1]);
40+
}
41+
42+
@Test
43+
void testLengthFive() {
44+
List<TreeSet<Integer>> result = ArrayCombination.combination(10, 5);
45+
assert result != null;
46+
Integer[] arr = result.get(0).toArray(new Integer[5]);
47+
assertEquals(1, arr[0]);
48+
assertEquals(5, arr[4]);
49+
}
50+
}

0 commit comments

Comments
 (0)