Skip to content

Commit a469160

Browse files
committed
Refactor EggDropping.java to improve readability and performance
1 parent 27deddc commit a469160

File tree

1 file changed

+37
-13
lines changed

1 file changed

+37
-13
lines changed

src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package com.thealgorithms.dynamicprogramming;
22

3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.api.Test;
7+
38
/**
49
* Dynamic Programming solution for the Egg Dropping Puzzle
510
* The problem is to find the minimum number of attempts needed in the worst case to find the critical
@@ -60,18 +65,37 @@ public static int minTrials(int eggs, int floors) {
6065
return dp[eggs][floors];
6166
}
6267

63-
/**
64-
* Example usage
65-
*/
66-
public static void main(String[] args) {
67-
try {
68-
// Example: 2 eggs and 4 floors
69-
System.out.println("Minimum number of trials in worst case with 2 eggs and 4 floors: " + minTrials(2, 4));
70-
71-
// Additional test case
72-
System.out.println("Minimum number of trials in worst case with 3 eggs and 5 floors: " + minTrials(3, 5));
73-
} catch (IllegalArgumentException e) {
74-
System.err.println("Error: " + e.getMessage());
75-
}
68+
@Test
69+
void testBasicScenarios() {
70+
// Test with 2 eggs and 4 floors
71+
assertEquals(3, minTrials(2, 4));
72+
73+
// Test with 3 eggs and 5 floors
74+
assertEquals(3, minTrials(3, 5));
75+
}
76+
77+
@Test
78+
void testEdgeCases() {
79+
// Test with single egg
80+
assertEquals(0, minTrials(1, 0));
81+
assertEquals(1, minTrials(1, 1));
82+
assertEquals(2, minTrials(1, 2));
83+
84+
// Test with multiple eggs but minimal floors
85+
assertEquals(0, minTrials(2, 0));
86+
assertEquals(1, minTrials(3, 1));
87+
}
88+
89+
@Test
90+
void testLargeInputs() {
91+
assertEquals(4, minTrials(3, 10));
92+
assertEquals(7, minTrials(2, 36));
93+
}
94+
95+
@Test
96+
void testInvalidInputs() {
97+
assertThrows(IllegalArgumentException.class, () -> minTrials(0, 5));
98+
assertThrows(IllegalArgumentException.class, () -> minTrials(-1, 5));
99+
assertThrows(IllegalArgumentException.class, () -> minTrials(2, -1));
76100
}
77101
}

0 commit comments

Comments
 (0)