* ArrayCombination function which uses Combination.java by creating an array of 1 to n * modified tests
This commit is contained in:
parent
b6563cf37a
commit
a7e76c57a0
@ -0,0 +1,29 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Finds all permutations of 1...n of length k
|
||||
* @author TheClerici (https://github.com/TheClerici)
|
||||
*/
|
||||
public class ArrayCombination {
|
||||
private static int length;
|
||||
|
||||
/**
|
||||
* Find all combinations of 1..n by creating an array and using backtracking in Combination.java
|
||||
* @param n max value of the array.
|
||||
* @param k length of combination
|
||||
* @return a list of all combinations of length k. If k == 0, return null.
|
||||
*/
|
||||
public static List<TreeSet<Integer>> combination(int n, int k) {
|
||||
if (n <= 0) {
|
||||
return null;
|
||||
}
|
||||
length = k;
|
||||
Integer[] arr = new Integer[n];
|
||||
for (int i = 1; i <= n; i++) {
|
||||
arr[i-1] = i;
|
||||
}
|
||||
return Combination.combination(arr, length);
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.TreeSet;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ArrayCombinationTest {
|
||||
|
||||
@Test
|
||||
void testNBeingZeroOrLess() {
|
||||
List<TreeSet<Integer>> zeroResult = ArrayCombination.combination(0, 1);
|
||||
List<TreeSet<Integer>> negativeResult = ArrayCombination.combination(-1, 1);
|
||||
assertNull(zeroResult);
|
||||
assertNull(negativeResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNoLengthElement() {
|
||||
List<TreeSet<Integer>> result = ArrayCombination.combination(2, 0);
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLengthOne() {
|
||||
List<TreeSet<Integer>> result = ArrayCombination.combination(2, 1);
|
||||
assert result != null;
|
||||
assertEquals(1, result.get(0).iterator().next());
|
||||
assertEquals(2, result.get(1).iterator().next());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLengthTwo() {
|
||||
List<TreeSet<Integer>> result = ArrayCombination.combination(2, 2);
|
||||
assert result != null;
|
||||
Integer[] arr = result.get(0).toArray(new Integer[2]);
|
||||
assertEquals(1, arr[0]);
|
||||
assertEquals(2, arr[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLengthFive() {
|
||||
List<TreeSet<Integer>> result = ArrayCombination.combination(10, 5);
|
||||
assert result != null;
|
||||
Integer[] arr = result.get(0).toArray(new Integer[5]);
|
||||
assertEquals(1, arr[0]);
|
||||
assertEquals(5, arr[4]);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user