|
1 | 1 | package com.thealgorithms.dynamicprogramming;
|
2 | 2 |
|
3 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals;
|
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
4 | 5 |
|
5 | 6 | import org.junit.jupiter.api.Test;
|
6 | 7 |
|
@@ -37,4 +38,41 @@ public void zeroCapacity() {
|
37 | 38 |
|
38 | 39 | assertEquals(0, KnapsackZeroOneTabulation.compute(values, weights, capacity, itemCount));
|
39 | 40 | }
|
| 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 | + } |
40 | 78 | }
|
0 commit comments