Skip to content

Commit 72ce8a2

Browse files
committed
Feat:add 0/1knapsack and 0/1knapsacktabulation along with their tests
1 parent 51fe605 commit 72ce8a2

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/test/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulationTest.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.thealgorithms.dynamicprogramming;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import org.junit.jupiter.api.Test;
67

@@ -37,4 +38,41 @@ public void zeroCapacity() {
3738

3839
assertEquals(0, KnapsackZeroOneTabulation.compute(values, weights, capacity, itemCount));
3940
}
41+
42+
@Test
43+
public void negativeCapacity() {
44+
int[] values = {10, 20, 30};
45+
int[] weights = {1, 1, 1};
46+
int capacity = -10;
47+
int itemCount = values.length;
48+
49+
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> KnapsackZeroOneTabulation.compute(values, weights, capacity, itemCount));
50+
assertEquals("Capacity must not be negative.", exception.getMessage());
51+
}
52+
53+
@Test
54+
public void mismatchedLengths() {
55+
int[] values = {60, 100}; // Only 2 values
56+
int[] weights = {10, 20, 30}; // 3 weights
57+
int capacity = 50;
58+
int itemCount = 2; // Matches `values.length`
59+
60+
// You could either expect 0 or throw an IllegalArgumentException in your compute function
61+
assertThrows(IllegalArgumentException.class, () -> { KnapsackZeroOneTabulation.compute(values, weights, capacity, itemCount); });
62+
}
63+
64+
@Test
65+
public void nullInputs() {
66+
int[] weights = {1, 2, 3};
67+
int capacity = 10;
68+
int itemCount = 3;
69+
70+
IllegalArgumentException exception1 = assertThrows(IllegalArgumentException.class, () -> KnapsackZeroOneTabulation.compute(null, weights, capacity, itemCount));
71+
assertEquals("Values and weights arrays must not be null.", exception1.getMessage());
72+
73+
int[] values = {1, 2, 3};
74+
75+
IllegalArgumentException exception2 = assertThrows(IllegalArgumentException.class, () -> KnapsackZeroOneTabulation.compute(values, null, capacity, itemCount));
76+
assertEquals("Values and weights arrays must not be null.", exception2.getMessage());
77+
}
4078
}

0 commit comments

Comments
 (0)