-
Notifications
You must be signed in to change notification settings - Fork 19.6k
/
Copy pathKnapsackTest.java
81 lines (71 loc) · 2.87 KB
/
KnapsackTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class KnapsackTest {
@Test
public void testKnapSackBasic() {
int[] weights = {2, 3, 4, 5};
int[] values = {3, 4, 5, 6};
int weightCapacity = 5;
int expected = 7; // Maximum value should be 7 (items 1 and 4).
int result = Knapsack.knapSack(weightCapacity, weights, values);
assertEquals(expected, result);
}
@Test
public void testKnapSackEmpty() {
int[] weights = {};
int[] values = {};
int weightCapacity = 10;
int expected = 0; // With no items, the result should be 0.
int result = Knapsack.knapSack(weightCapacity, weights, values);
assertEquals(expected, result);
}
@Test
public void testKnapSackNoCapacity() {
int[] weights = {2, 3, 4};
int[] values = {3, 4, 5};
int weightCapacity = 0;
int expected = 0; // With no capacity, the result should be 0.
int result = Knapsack.knapSack(weightCapacity, weights, values);
assertEquals(expected, result);
}
@Test
public void testKnapSackMaxCapacity() {
int[] weights = {2, 3, 4, 5};
int[] values = {3, 4, 5, 6};
int weightCapacity = 10;
int expected = 13; // Maximum value should be 13 (items 1, 3, and 4).
int result = Knapsack.knapSack(weightCapacity, weights, values);
assertEquals(expected, result);
}
@Test
public void testKnapSackThrowsForInputsOfDifferentLength() {
int[] weights = {2, 3, 4};
int[] values = {3, 4, 5, 6}; // Different length values array.
int weightCapacity = 5;
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, values); });
}
@Test
public void testKnapSackThrowsForNullInputs() {
int[] weights = {2, 3, 4};
int[] values = {3, 4, 6};
int weightCapacity = 5;
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, null, values); });
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, null); });
}
@Test
public void testKnapSackThrowsForNegativeCapacity() {
int[] weights = {2, 3, 4, 5};
int[] values = {3, 4, 5, 6};
int weightCapacity = -5;
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, values); });
}
@Test
public void testKnapSackThrowsForNegativeWeight() {
int[] weights = {2, 0, 4};
int[] values = {3, 4, 6};
int weightCapacity = 5;
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, values); });
}
}