diff --git a/pom.xml b/pom.xml
index 924a736d526d..a152eda16972 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,159 +1,236 @@
-
-
- 4.0.0
- com.thealgorithms
- Java
- 1.0-SNAPSHOT
- jar
-
-
- UTF-8
- 21
- 21
- 3.26.0
-
-
-
-
-
- org.junit
- junit-bom
- 5.10.3
- pom
- import
-
-
-
-
+
+
+ 4.0.0
+ com.thealgorithms
+ Java
+ 1.0-SNAPSHOT
+ jar
+
+ UTF-8
+ 21
+ 21
+ 3.26.0
+
+
-
- org.junit.jupiter
- junit-jupiter
- 5.10.3
- test
-
-
- org.assertj
- assertj-core
- ${assertj.version}
- test
-
-
-
- org.junit.jupiter
- junit-jupiter-api
- 5.10.3
- test
-
-
- org.apache.commons
- commons-lang3
- 3.14.0
-
-
- org.apache.commons
- commons-collections4
- 4.5.0-M2
-
+
+ org.junit
+ junit-bom
+ 5.10.3
+ pom
+ import
+
+
+ io.spring.javaformat
+ spring-javaformat-formatter
+ 0.0.40
+
+
+
+ org.assertj
+ assertj-guava
+ 3.26.0
+ compile
+
+
+
+ org.assertj
+ assertj-db
+ 2.0.2
+ compile
+
+
+
+ org.assertj
+ assertj-joda-time
+ 2.2.0
+ compile
+
+
-
-
-
-
- maven-surefire-plugin
- 3.3.0
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.13.0
-
- 21
- 21
-
- -Xlint:all
- -Xlint:-auxiliaryclass
- -Xlint:-rawtypes
- -Xlint:-unchecked
- -Xlint:-lossy-conversions
- -Werror
-
-
-
-
- org.jacoco
- jacoco-maven-plugin
- 0.8.12
-
-
-
- prepare-agent
-
-
-
- generate-code-coverage-report
- test
-
- report
-
-
-
-
-
- org.apache.maven.plugins
- maven-checkstyle-plugin
- 3.4.0
-
- checkstyle.xml
- true
- true
- warning
-
-
-
- com.puppycrawl.tools
- checkstyle
- 10.17.0
-
-
-
+
+
+
+ org.junit.jupiter
+ junit-jupiter
+ 5.10.3
+ test
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ 5.10.3
+ test
+
+
+ org.apache.commons
+ commons-lang3
+ 3.14.0
+
+
+ org.apache.commons
+ commons-collections4
+ 4.5.0-M2
+
+
+ io.spring.javaformat
+ spring-javaformat-formatter
+ 0.0.40
+
+
+
+ org.assertj
+ assertj-guava
+ 3.26.0
+ compile
+
+
+
+ org.assertj
+ assertj-db
+ 2.0.2
+ compile
+
+
+
+ org.assertj
+ assertj-joda-time
+ 2.2.0
+ compile
+
+
+
+
+
+
+ maven-surefire-plugin
+ 3.3.0
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.13.0
+
+ 21
+ 21
+
+ -Xlint:all
+ -Xlint:-auxiliaryclass
+ -Xlint:-rawtypes
+ -Xlint:-unchecked
+ -Xlint:-lossy-conversions
+ -Werror
+
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+ 0.8.12
+
+
+
+ prepare-agent
+
+
+
+ generate-code-coverage-report
+ test
+
+ report
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ 3.4.0
+
+ checkstyle.xml
+ true
+ true
+ warning
+
+
+
+ com.puppycrawl.tools
+ checkstyle
+ 10.17.0
+
+
+
+
+ com.github.spotbugs
+ spotbugs-maven-plugin
+ 4.8.6.1
+
+ spotbugs-exclude.xml
+ true
+
- com.github.spotbugs
- spotbugs-maven-plugin
- 4.8.6.1
-
- spotbugs-exclude.xml
- true
-
-
- com.mebigfatguy.fb-contrib
- fb-contrib
- 7.6.4
-
-
- com.h3xstream.findsecbugs
- findsecbugs-plugin
- 1.13.0
-
-
-
+ com.mebigfatguy.fb-contrib
+ fb-contrib
+ 7.6.4
- org.apache.maven.plugins
- maven-pmd-plugin
- 3.23.0
-
- true
- true
- false
- pmd-exclude.properties
-
+ com.h3xstream.findsecbugs
+ findsecbugs-plugin
+ 1.13.0
-
-
-
+
+
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+ 3.23.0
+
+ true
+ true
+ false
+ pmd-exclude.properties
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.2.5
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-report-plugin
+ 3.2.5
+
+ testReport
+
+
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 2.1
+
+ testReport
+
+
+
+
+ io.spring.javaformat
+ spring-javaformat-maven-plugin
+ 0.0.40
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionActivitySelectionTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionActivitySelectionTest.java
new file mode 100644
index 000000000000..5e9680c5c279
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionActivitySelectionTest.java
@@ -0,0 +1,222 @@
+// ********RoostGPT********
+/*
+Test generated by RoostGPT for test java-algos using AI Type Claude AI and AI Model claude-3-5-sonnet-20240620
+ROOST_METHOD_HASH=activitySelection_77631a6e2d
+ROOST_METHOD_SIG_HASH=activitySelection_bf79d28a9f
+================================VULNERABILITIES================================
+Vulnerability: cwe-190: integer overflow or wraparound
+Issue: The code uses int for array indices and lengths, which could lead to integer overflow if very large input arrays are provided. This could result in unexpected behavior or crashes.
+Solution: Use long instead of int for array indices and lengths, or implement input validation to ensure array sizes are within safe limits.
+Vulnerability: cwe-400: uncontrolled resource consumption
+Issue: The method doesn't limit the size of input arrays, potentially leading to excessive memory consumption or processing time with large inputs.
+Solution: Implement input validation to limit the maximum size of input arrays, or use a more memory-efficient algorithm for large inputs.
+Vulnerability: cwe-476: null pointer dereference
+Issue: The method doesn't check if input arrays are null before accessing them, which could lead to NullPointerException.
+Solution: Add null checks for input arrays at the beginning of the method and throw an appropriate exception if they are null.
+Vulnerability: cwe-597: use of wrong operator in string comparison
+Issue: While not directly present in this code, developers using this method might mistakenly use '==' instead of '.equals()' when comparing activity indices, leading to unexpected behavior.
+Solution: Add a comment or documentation emphasizing the use of '.equals()' for comparing Integer objects when working with the returned ArrayList.
+================================================================================
+Based on the provided method and imports, here are several test scenarios for the `activitySelection` method:
+```
+Scenario 1: Basic Activity Selection
+Details:
+ TestName: basicActivitySelection
+ Description: Test the basic functionality of activity selection with a simple set of non-overlapping activities.
+Execution:
+ Arrange: Create arrays for start times and end times with non-overlapping activities.
+ Act: Call activitySelection with the arranged start and end times.
+ Assert: Verify that the returned ArrayList contains the expected activity indices in the correct order.
+Validation:
+ This test ensures that the method correctly selects all activities when they don't overlap. It validates the core functionality of the activity selection algorithm.
+Scenario 2: Overlapping Activities
+Details:
+ TestName: overlappingActivities
+ Description: Test the method's ability to select the maximum number of non-overlapping activities from a set of overlapping activities.
+Execution:
+ Arrange: Create arrays for start times and end times with some overlapping activities.
+ Act: Call activitySelection with the arranged start and end times.
+ Assert: Verify that the returned ArrayList contains the indices of the maximum set of non-overlapping activities.
+Validation:
+ This test checks if the method correctly handles overlapping activities and selects the optimal set of non-overlapping activities. It validates the core logic of the greedy algorithm used in activity selection.
+Scenario 3: Empty Input Arrays
+Details:
+ TestName: emptyInputArrays
+ Description: Test the method's behavior when given empty input arrays.
+Execution:
+ Arrange: Create empty arrays for start times and end times.
+ Act: Call activitySelection with the empty arrays.
+ Assert: Verify that the method returns an empty ArrayList.
+Validation:
+ This test ensures that the method handles edge cases correctly, specifically when no activities are provided. It's important to validate that the method doesn't throw exceptions and returns an expected result for edge cases.
+Scenario 4: Single Activity
+Details:
+ TestName: singleActivity
+ Description: Test the method's behavior when given a single activity.
+Execution:
+ Arrange: Create arrays for start times and end times with only one activity.
+ Act: Call activitySelection with the single-activity arrays.
+ Assert: Verify that the returned ArrayList contains only one element with the index 0.
+Validation:
+ This test checks if the method correctly handles the case of a single activity, ensuring it's selected and returned properly. It's a boundary case that needs to be validated.
+Scenario 5: Activities with Same End Time
+Details:
+ TestName: activitiesWithSameEndTime
+ Description: Test the method's behavior when multiple activities have the same end time.
+Execution:
+ Arrange: Create arrays for start times and end times where multiple activities end at the same time.
+ Act: Call activitySelection with the arranged start and end times.
+ Assert: Verify that the returned ArrayList contains the correct selection of activities, prioritizing those with earlier start times when end times are the same.
+Validation:
+ This test ensures that the method correctly handles activities with identical end times, which tests the stability of the sorting algorithm and the selection process.
+Scenario 6: Activities with Same Start Time
+Details:
+ TestName: activitiesWithSameStartTime
+ Description: Test the method's behavior when multiple activities have the same start time.
+Execution:
+ Arrange: Create arrays for start times and end times where multiple activities start at the same time.
+ Act: Call activitySelection with the arranged start and end times.
+ Assert: Verify that the returned ArrayList contains the correct selection of activities, prioritizing those with earlier end times.
+Validation:
+ This test checks if the method correctly handles activities with identical start times, ensuring that the selection is based on end times in such cases.
+Scenario 7: Large Number of Activities
+Details:
+ TestName: largeNumberOfActivities
+ Description: Test the method's performance and correctness with a large number of activities.
+Execution:
+ Arrange: Create large arrays for start times and end times with many activities.
+ Act: Call activitySelection with the large arrays.
+ Assert: Verify that the returned ArrayList contains a correct selection of non-overlapping activities and that the execution time is within acceptable limits.
+Validation:
+ This test ensures that the method scales well with a large number of activities and maintains correctness. It helps validate the efficiency of the algorithm implementation.
+```
+These test scenarios cover various aspects of the `activitySelection` method, including basic functionality, edge cases, and potential performance considerations. They aim to validate the correctness and robustness of the implementation across different input scenarios.
+*/
+// ********RoostGPT********
+package com.thealgorithms.greedyalgorithms;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.stream.Stream;
+import java.util.Comparator;
+import org.junit.jupiter.api.*;
+
+@Tag("com.thealgorithms.sorts")
+@Tag("com.thealgorithms.sorts.sort")
+@Tag("com.thealgorithms.misc")
+@Tag("com.thealgorithms.misc.add")
+@Tag("com.thealgorithms.misc.add")
+@Tag("com.thealgorithms.greedyalgorithms")
+@Tag("com.thealgorithms.greedyalgorithms.activitySelection")
+class ActivitySelectionActivitySelectionTest {
+
+ @Test
+ void basicActivitySelection() {
+ int[] startTimes = { 1, 3, 0, 5, 8, 5 };
+ int[] endTimes = { 2, 4, 6, 7, 9, 9 };
+ ArrayList expected = new ArrayList<>(Arrays.asList(0, 1, 3, 4));
+
+ ArrayList result = ActivitySelection.activitySelection(startTimes, endTimes);
+
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @Test
+ void overlappingActivities() {
+ int[] startTimes = { 1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12 };
+ int[] endTimes = { 4, 5, 6, 7, 9, 9, 10, 11, 12, 14, 16 };
+ ArrayList expected = new ArrayList<>(Arrays.asList(0, 3, 7, 10));
+
+ ArrayList result = ActivitySelection.activitySelection(startTimes, endTimes);
+
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @Test
+ void emptyInputArrays() {
+ int[] startTimes = {};
+ int[] endTimes = {};
+ ArrayList expected = new ArrayList<>();
+
+ ArrayList result = ActivitySelection.activitySelection(startTimes, endTimes);
+
+ assertThat(result).isEmpty();
+ }
+
+ @Test
+ void singleActivity() {
+ int[] startTimes = { 1 };
+ int[] endTimes = { 2 };
+ ArrayList expected = new ArrayList<>(Arrays.asList(0));
+
+ ArrayList result = ActivitySelection.activitySelection(startTimes, endTimes);
+
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @Test
+ void activitiesWithSameEndTime() {
+ int[] startTimes = { 1, 3, 2, 5 };
+ int[] endTimes = { 4, 4, 4, 6 };
+ ArrayList expected = new ArrayList<>(Arrays.asList(0, 3));
+
+ ArrayList result = ActivitySelection.activitySelection(startTimes, endTimes);
+
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @Test
+ void activitiesWithSameStartTime() {
+ int[] startTimes = { 1, 1, 1, 4 };
+ int[] endTimes = { 2, 3, 4, 5 };
+ ArrayList expected = new ArrayList<>(Arrays.asList(0, 3));
+
+ ArrayList result = ActivitySelection.activitySelection(startTimes, endTimes);
+
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @Test
+ void largeNumberOfActivities() {
+ int[] startTimes = new int[1000];
+ int[] endTimes = new int[1000];
+ for (int i = 0; i < 1000; i++) {
+ startTimes[i] = i;
+ endTimes[i] = i + 1;
+ }
+ ArrayList expected = new ArrayList<>();
+ for (int i = 0; i < 1000; i++) {
+ expected.add(i);
+ }
+
+ ArrayList result = ActivitySelection.activitySelection(startTimes, endTimes);
+
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("provideTestCases")
+ void parameterizedActivitySelectionTest(int[] startTimes, int[] endTimes, ArrayList expected) {
+ ArrayList result = ActivitySelection.activitySelection(startTimes, endTimes);
+ assertThat(result).isEqualTo(expected);
+ }
+
+ private static Stream provideTestCases() {
+ return Stream.of(
+ Arguments.of(new int[] { 1, 3, 0, 5, 8, 5 }, new int[] { 2, 4, 6, 7, 9, 9 },
+ new ArrayList<>(Arrays.asList(0, 1, 3, 4))),
+ Arguments.of(new int[] { 1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12 },
+ new int[] { 4, 5, 6, 7, 9, 9, 10, 11, 12, 14, 16 },
+ new ArrayList<>(Arrays.asList(0, 3, 7, 10))),
+ Arguments.of(new int[] {}, new int[] {}, new ArrayList<>()),
+ Arguments.of(new int[] { 1 }, new int[] { 2 }, new ArrayList<>(Arrays.asList(0))),
+ Arguments.of(new int[] { 1, 3, 2, 5 }, new int[] { 4, 4, 4, 6 }, new ArrayList<>(Arrays.asList(0, 3))),
+ Arguments.of(new int[] { 1, 1, 1, 4 }, new int[] { 2, 3, 4, 5 }, new ArrayList<>(Arrays.asList(0, 3))));
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeCoinChangeProblemTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeCoinChangeProblemTest.java
new file mode 100644
index 000000000000..c8de6e5e43e1
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeCoinChangeProblemTest.java
@@ -0,0 +1,172 @@
+// ********RoostGPT********
+/*
+Test generated by RoostGPT for test java-algos using AI Type Claude AI and AI Model claude-3-5-sonnet-20240620
+ROOST_METHOD_HASH=coinChangeProblem_db77356e05
+ROOST_METHOD_SIG_HASH=coinChangeProblem_9cb8b5505c
+================================VULNERABILITIES================================
+Vulnerability: integer overflow
+Issue: The 'amount' parameter in coinChangeProblem() method could potentially overflow if a large value is provided, leading to unexpected behavior or incorrect results.
+Solution: Use BigInteger instead of int for large currency amounts, or implement input validation to ensure 'amount' is within a safe range.
+Vulnerability: denial of service
+Issue: If a malicious user provides an extremely large 'amount', it could lead to excessive resource consumption and potential denial of service.
+Solution: Implement an upper bound check for the 'amount' parameter and throw an exception if it exceeds a reasonable maximum value.
+Vulnerability: inefficient algorithm
+Issue: While not a direct security vulnerability, the current greedy algorithm may not always produce the optimal solution, which could be exploited in financial applications.
+Solution: Consider using a dynamic programming approach for coin change problem to ensure optimal solutions, especially for critical financial calculations.
+================================================================================
+Based on the provided method and instructions, here are several JUnit test scenarios for the `coinChangeProblem` method:
+```
+Scenario 1: Test with a small amount
+Details:
+ TestName: smallAmountChange
+ Description: Verify that the method correctly handles a small amount that can be made with a combination of available coins.
+Execution:
+ Arrange: Set up the test amount (e.g., 67)
+ Act: Call coinChangeProblem(67)
+ Assert: Check if the returned ArrayList contains the expected coins [50, 10, 5, 2]
+Validation:
+ This test ensures that the method correctly breaks down a small amount into the largest possible denominations. It verifies that the greedy algorithm works for a simple case.
+Scenario 2: Test with a large amount
+Details:
+ TestName: largeAmountChange
+ Description: Verify that the method correctly handles a large amount that requires using the highest denomination multiple times.
+Execution:
+ Arrange: Set up the test amount (e.g., 4578)
+ Act: Call coinChangeProblem(4578)
+ Assert: Check if the returned ArrayList contains the expected coins [2000, 2000, 500, 50, 20, 5, 2, 1]
+Validation:
+ This test verifies that the method can handle larger amounts and correctly uses the highest denominations multiple times when necessary.
+Scenario 3: Test with an amount that matches a single coin denomination
+Details:
+ TestName: exactDenominationAmount
+ Description: Verify that the method returns a single coin when the amount exactly matches a coin denomination.
+Execution:
+ Arrange: Set up the test amount (e.g., 100)
+ Act: Call coinChangeProblem(100)
+ Assert: Check if the returned ArrayList contains only one coin [100]
+Validation:
+ This test ensures that the method correctly handles cases where the amount can be satisfied with a single coin, demonstrating efficient coin selection.
+Scenario 4: Test with zero amount
+Details:
+ TestName: zeroAmountChange
+ Description: Verify that the method returns an empty list when the input amount is zero.
+Execution:
+ Arrange: Set up the test amount as 0
+ Act: Call coinChangeProblem(0)
+ Assert: Check if the returned ArrayList is empty
+Validation:
+ This test verifies that the method correctly handles the edge case of zero amount, returning an empty list as no coins are needed.
+Scenario 5: Test with an amount smaller than the smallest coin denomination
+Details:
+ TestName: amountSmallerThanSmallestCoin
+ Description: Verify that the method correctly handles an amount smaller than the smallest available coin.
+Execution:
+ Arrange: Set up the test amount as 0.5 (assuming the smallest coin is 1)
+ Act: Call coinChangeProblem(0)
+ Assert: Check if the returned ArrayList is empty
+Validation:
+ This test ensures that the method correctly handles amounts smaller than the smallest available coin, returning an empty list as no valid solution exists.
+Scenario 6: Test with a large prime number amount
+Details:
+ TestName: largePrimeAmountChange
+ Description: Verify that the method correctly handles a large prime number amount that requires using many small denominations.
+Execution:
+ Arrange: Set up the test amount (e.g., 2017)
+ Act: Call coinChangeProblem(2017)
+ Assert: Check if the returned ArrayList contains the expected coins [2000, 10, 5, 2]
+Validation:
+ This test verifies that the method can handle large prime numbers efficiently, using a combination of large and small denominations.
+Scenario 7: Test with maximum possible amount
+Details:
+ TestName: maxPossibleAmountChange
+ Description: Verify that the method correctly handles the maximum possible amount that can be represented by Integer.MAX_VALUE.
+Execution:
+ Arrange: Set up the test amount as Integer.MAX_VALUE
+ Act: Call coinChangeProblem(Integer.MAX_VALUE)
+ Assert: Check if the returned ArrayList contains the correct number and combination of coins
+Validation:
+ This test ensures that the method can handle the maximum possible integer value without overflow or other issues, demonstrating its robustness for extreme cases.
+```
+These test scenarios cover various aspects of the `coinChangeProblem` method, including normal cases, edge cases, and potential error conditions. They aim to verify the correct functionality of the method across different input ranges and scenarios.
+*/
+// ********RoostGPT********
+package com.thealgorithms.greedyalgorithms;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.stream.Stream;
+import java.util.Comparator;
+import org.junit.jupiter.api.*;
+
+@Tag("com.thealgorithms.sorts")
+@Tag("com.thealgorithms.sorts.sort")
+@Tag("com.thealgorithms.misc")
+@Tag("com.thealgorithms.misc.add")
+@Tag("com.thealgorithms.greedyalgorithms")
+@Tag("com.thealgorithms.greedyalgorithms.coinChangeProblem")
+class CoinChangeCoinChangeProblemTest {
+
+ @ParameterizedTest
+ @MethodSource("provideTestCases")
+ void testCoinChangeProblem(int amount, ArrayList expected) {
+ ArrayList result = CoinChange.coinChangeProblem(amount);
+ assertThat(result).isEqualTo(expected);
+ }
+
+ private static Stream provideTestCases() {
+ return Stream.of(Arguments.of(67, new ArrayList<>(Arrays.asList(50, 10, 5, 2))),
+ Arguments.of(4578, new ArrayList<>(Arrays.asList(2000, 2000, 500, 50, 20, 5, 2, 1))),
+ Arguments.of(100, new ArrayList<>(Arrays.asList(100))), Arguments.of(0, new ArrayList<>()),
+ Arguments.of(2017, new ArrayList<>(Arrays.asList(2000, 10, 5, 2))));
+ }
+
+ @Test
+ void testSmallAmountChange() {
+ ArrayList result = CoinChange.coinChangeProblem(67);
+ assertThat(result).containsExactly(50, 10, 5, 2);
+ }
+
+ @Test
+ void testLargeAmountChange() {
+ ArrayList result = CoinChange.coinChangeProblem(4578);
+ assertThat(result).containsExactly(2000, 2000, 500, 50, 20, 5, 2, 1);
+ }
+
+ @Test
+ void testExactDenominationAmount() {
+ ArrayList result = CoinChange.coinChangeProblem(100);
+ assertThat(result).containsExactly(100);
+ }
+
+ @Test
+ void testZeroAmountChange() {
+ ArrayList result = CoinChange.coinChangeProblem(0);
+ assertThat(result).isEmpty();
+ }
+
+ @Test
+ void testAmountSmallerThanSmallestCoin() {
+ ArrayList result = CoinChange.coinChangeProblem(0);
+ assertThat(result).isEmpty();
+ }
+
+ @Test
+ void testLargePrimeAmountChange() {
+ ArrayList result = CoinChange.coinChangeProblem(2017);
+ assertThat(result).containsExactly(2000, 10, 5, 2);
+ }
+
+ @Test
+ void testMaxPossibleAmountChange() {
+ ArrayList result = CoinChange.coinChangeProblem(Integer.MAX_VALUE);
+ assertThat(result).isNotEmpty();
+ int sum = result.stream().mapToInt(Integer::intValue).sum();
+ assertThat(sum).isEqualTo(Integer.MAX_VALUE);
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackFractionalKnapsackTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackFractionalKnapsackTest.java
new file mode 100644
index 000000000000..074475dfd6aa
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackFractionalKnapsackTest.java
@@ -0,0 +1,194 @@
+// ********RoostGPT********
+/*
+Test generated by RoostGPT for test java-algos using AI Type Claude AI and AI Model claude-3-5-sonnet-20240620
+ROOST_METHOD_HASH=fractionalKnapsack_b327dd7d5e
+ROOST_METHOD_SIG_HASH=fractionalKnapsack_1caf503527
+================================VULNERABILITIES================================
+Vulnerability: integer overflow
+Issue: The calculation of finalValue += (int) (ratio[i][1] * current) may lead to integer overflow if the result exceeds Integer.MAX_VALUE.
+Solution: Use long or BigInteger for finalValue to handle larger values, or implement overflow checks before addition.
+Vulnerability: floating-point precision
+Issue: Using double for ratio calculations may lead to precision errors, potentially affecting the accuracy of the knapsack algorithm.
+Solution: Consider using BigDecimal for precise decimal arithmetic, especially when dealing with financial calculations or when high precision is required.
+Vulnerability: array index out of bounds
+Issue: If the input arrays weight and value have different lengths, it may cause ArrayIndexOutOfBoundsException.
+Solution: Add a check at the beginning of the method to ensure that weight.length == value.length, throwing an IllegalArgumentException if they don't match.
+Vulnerability: null pointer dereference
+Issue: The method doesn't check if the input arrays weight and value are null, which could lead to NullPointerException.
+Solution: Add null checks for input parameters at the beginning of the method, throwing NullPointerException with appropriate error messages if null is detected.
+Vulnerability: integer division
+Issue: The calculation ratio[i][1] = value[i] / (double) weight[i] may result in division by zero if weight[i] is 0.
+Solution: Add a check to ensure weight[i] is not zero before performing the division. Handle zero weights appropriately, either by skipping the item or assigning a special value.
+================================================================================
+Based on the provided method and instructions, here are several test scenarios for the fractionalKnapsack method:
+Scenario 1: Basic Functionality Test
+Details:
+ TestName: basicFunctionalityTest
+ Description: Verify that the method correctly calculates the maximum value for a simple knapsack problem.
+Execution:
+ Arrange: Create arrays for weights, values, and set a capacity.
+ Act: Call fractionalKnapsack with the prepared data.
+ Assert: Compare the returned value with the expected maximum value.
+Validation:
+ This test ensures that the basic algorithm works correctly for a straightforward case. It's crucial to verify that the method can handle a simple scenario before testing more complex cases.
+Scenario 2: Full Capacity Utilization
+Details:
+ TestName: fullCapacityUtilization
+ Description: Test when the knapsack can be filled to its exact capacity with whole items.
+Execution:
+ Arrange: Set up weight and value arrays where items can perfectly fill the knapsack.
+ Act: Invoke fractionalKnapsack with these arrays and the exact capacity.
+ Assert: Check if the returned value matches the sum of all item values.
+Validation:
+ This test verifies that the method correctly handles cases where no fractional items are needed, utilizing the full capacity efficiently.
+Scenario 3: Fractional Item Inclusion
+Details:
+ TestName: fractionalItemInclusion
+ Description: Verify that the method correctly includes a fraction of an item to maximize value.
+Execution:
+ Arrange: Create arrays where the last item needs to be fractionally included.
+ Act: Call fractionalKnapsack with these arrays and a capacity that requires fractional inclusion.
+ Assert: Confirm that the returned value includes the correct fractional value of the last item.
+Validation:
+ This test is critical to ensure that the fractional aspect of the algorithm works correctly, which is a key feature of the fractional knapsack problem.
+Scenario 4: Empty Input Arrays
+Details:
+ TestName: emptyInputArrays
+ Description: Test the method's behavior when given empty weight and value arrays.
+Execution:
+ Arrange: Create empty weight and value arrays.
+ Act: Call fractionalKnapsack with empty arrays and a positive capacity.
+ Assert: Verify that the method returns 0 or handles empty inputs appropriately.
+Validation:
+ This test checks the method's robustness in handling edge cases, specifically when no items are available.
+Scenario 5: Zero Capacity Knapsack
+Details:
+ TestName: zeroCapacityKnapsack
+ Description: Verify the method's response when the knapsack capacity is zero.
+Execution:
+ Arrange: Set up normal weight and value arrays.
+ Act: Invoke fractionalKnapsack with these arrays but set capacity to 0.
+ Assert: Confirm that the method returns 0 as no items can be included.
+Validation:
+ This test ensures that the method correctly handles the edge case of a knapsack with no capacity, preventing any erroneous calculations.
+Scenario 6: Single Item Larger Than Capacity
+Details:
+ TestName: singleItemLargerThanCapacity
+ Description: Test when there's only one item and its weight exceeds the knapsack capacity.
+Execution:
+ Arrange: Create arrays with a single item whose weight is greater than the capacity.
+ Act: Call fractionalKnapsack with these single-item arrays and a smaller capacity.
+ Assert: Check if the returned value is the correct fraction of the item's value.
+Validation:
+ This test verifies that the method correctly calculates fractional value when the entire item cannot fit, which is crucial for the fractional knapsack algorithm.
+Scenario 7: Items with Zero Weight
+Details:
+ TestName: itemsWithZeroWeight
+ Description: Verify how the method handles items with zero weight.
+Execution:
+ Arrange: Set up arrays including items with zero weight but positive value.
+ Act: Invoke fractionalKnapsack with these arrays and a positive capacity.
+ Assert: Confirm that zero-weight items are correctly handled and included in the final value.
+Validation:
+ This test checks the method's ability to handle potential division by zero and ensures that valuable items with no weight are correctly included.
+These scenarios cover various aspects of the fractionalKnapsack method, including basic functionality, edge cases, and potential error conditions. They aim to thoroughly test the method's correctness and robustness.
+*/
+// ********RoostGPT********
+package com.thealgorithms.greedyalgorithms;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import static org.junit.jupiter.api.Assertions.*;
+import java.util.stream.Stream;
+import java.util.Arrays;
+import java.util.Comparator;
+import org.junit.jupiter.api.*;
+
+@Tag("com.thealgorithms.sorts")
+@Tag("com.thealgorithms.sorts.sort")
+@Tag("com.thealgorithms.greedyalgorithms")
+@Tag("com.thealgorithms.greedyalgorithms.fractionalKnapsack")
+class FractionalKnapsackFractionalKnapsackTest {
+
+ @Test
+ void basicFunctionalityTest() {
+ int[] weights = { 10, 20, 30 };
+ int[] values = { 60, 100, 120 };
+ int capacity = 50;
+ int expectedValue = 240;
+ assertEquals(expectedValue, FractionalKnapsack.fractionalKnapsack(weights, values, capacity));
+ }
+
+ @Test
+ void fullCapacityUtilization() {
+ int[] weights = { 10, 20, 30 };
+ int[] values = { 60, 100, 120 };
+ int capacity = 60;
+ int expectedValue = 280;
+ assertEquals(expectedValue, FractionalKnapsack.fractionalKnapsack(weights, values, capacity));
+ }
+
+ @Test
+ void fractionalItemInclusion() {
+ int[] weights = { 10, 20, 30 };
+ int[] values = { 60, 100, 120 };
+ int capacity = 55;
+ int expectedValue = 260;
+ assertEquals(expectedValue, FractionalKnapsack.fractionalKnapsack(weights, values, capacity));
+ }
+
+ @Test
+ void emptyInputArrays() {
+ int[] weights = {};
+ int[] values = {};
+ int capacity = 50;
+ int expectedValue = 0;
+ assertEquals(expectedValue, FractionalKnapsack.fractionalKnapsack(weights, values, capacity));
+ }
+
+ @Test
+ void zeroCapacityKnapsack() {
+ int[] weights = { 10, 20, 30 };
+ int[] values = { 60, 100, 120 };
+ int capacity = 0;
+ int expectedValue = 0;
+ assertEquals(expectedValue, FractionalKnapsack.fractionalKnapsack(weights, values, capacity));
+ }
+
+ @Test
+ void singleItemLargerThanCapacity() {
+ int[] weights = { 100 };
+ int[] values = { 500 };
+ int capacity = 50;
+ int expectedValue = 250;
+ assertEquals(expectedValue, FractionalKnapsack.fractionalKnapsack(weights, values, capacity));
+ }
+
+ @Test
+ void itemsWithZeroWeight() {
+ int[] weights = { 0, 20, 30 };
+ int[] values = { 50, 100, 120 };
+ int capacity = 50;
+ int expectedValue = 270;
+ assertEquals(expectedValue, FractionalKnapsack.fractionalKnapsack(weights, values, capacity));
+ }
+
+ @ParameterizedTest
+ @MethodSource("provideTestCases")
+ void parameterizedTest(int[] weights, int[] values, int capacity, int expectedValue) {
+ assertEquals(expectedValue, FractionalKnapsack.fractionalKnapsack(weights, values, capacity));
+ }
+
+ private static Stream provideTestCases() {
+ return Stream.of(Arguments.of(new int[] { 10, 20, 30 }, new int[] { 60, 100, 120 }, 50, 240),
+ Arguments.of(new int[] { 10, 20, 30 }, new int[] { 60, 100, 120 }, 60, 280),
+ Arguments.of(new int[] { 10, 20, 30 }, new int[] { 60, 100, 120 }, 55, 260),
+ Arguments.of(new int[] {}, new int[] {}, 50, 0),
+ Arguments.of(new int[] { 10, 20, 30 }, new int[] { 60, 100, 120 }, 0, 0),
+ Arguments.of(new int[] { 100 }, new int[] { 500 }, 50, 250),
+ Arguments.of(new int[] { 0, 20, 30 }, new int[] { 50, 100, 120 }, 50, 270));
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingFindJobSequenceTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingFindJobSequenceTest.java
new file mode 100644
index 000000000000..9d5ae2223e61
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingFindJobSequenceTest.java
@@ -0,0 +1,208 @@
+// ********RoostGPT********
+/*
+Test generated by RoostGPT for test java-algos using AI Type Claude AI and AI Model claude-3-5-sonnet-20240620
+ROOST_METHOD_HASH=findJobSequence_a922574874
+ROOST_METHOD_SIG_HASH=findJobSequence_1dce91ae26
+================================VULNERABILITIES================================
+Vulnerability: cwe-190: integer overflow
+Issue: The code uses 'int' for array indices and loop counters, which could lead to integer overflow if the input size is very large. This could result in unexpected behavior or crashes.
+Solution: Use 'long' instead of 'int' for array indices and loop counters when dealing with potentially large inputs. Consider adding input validation to ensure the size is within reasonable bounds.
+Vulnerability: cwe-476: null pointer dereference
+Issue: The code assumes that 'jobs' ArrayList is not null and contains elements. If 'jobs' is null or empty, it could lead to a NullPointerException.
+Solution: Add null checks and size checks before accessing the 'jobs' ArrayList. For example: if (jobs == null || jobs.isEmpty()) { return 'No jobs available'; }
+Vulnerability: cwe-129: improper array index validation
+Issue: The code accesses array elements without proper bounds checking, which could lead to ArrayIndexOutOfBoundsException if the job's deadline is greater than the size of the slots array.
+Solution: Add bounds checking before accessing array elements. Ensure that the job's deadline does not exceed the size of the slots array.
+Vulnerability: cwe-597: use of wrong operator in string comparison
+Issue: The code uses '==' to compare Boolean objects, which compares object references instead of values. This could lead to unexpected behavior.
+Solution: Use the equals() method for comparing Boolean objects, or use primitive boolean values instead of Boolean objects.
+Vulnerability: cwe-134: uncontrolled format string
+Issue: The code concatenates user-supplied data (job IDs) directly into the output string, which could lead to format string vulnerabilities if the job IDs contain format specifiers.
+Solution: Use StringBuilder's append() method with proper escaping or formatting to prevent potential format string vulnerabilities.
+================================================================================
+Based on the provided method and imports, here are several test scenarios for the `findJobSequence` method:
+Scenario 1: Normal Job Sequence with Multiple Jobs
+Details:
+ TestName: normalJobSequenceWithMultipleJobs
+ Description: Test the method with a normal set of jobs to ensure it returns the correct job sequence.
+Execution:
+ Arrange: Create an ArrayList of Job objects with various deadlines and profits. Set the size parameter.
+ Act: Call findJobSequence with the created ArrayList and size.
+ Assert: Check if the returned string matches the expected job sequence.
+Validation:
+ Verify that the method correctly identifies and orders jobs based on their deadlines and profits. This test ensures the core functionality of the job sequencing algorithm works as expected.
+Scenario 2: Empty Job List
+Details:
+ TestName: emptyJobList
+ Description: Test the method's behavior when given an empty list of jobs.
+Execution:
+ Arrange: Create an empty ArrayList of Job objects. Set size to 0.
+ Act: Call findJobSequence with the empty ArrayList and size 0.
+ Assert: Check if the returned string is "Job Sequence: " (empty sequence).
+Validation:
+ Ensure the method handles empty input gracefully without throwing exceptions and returns an appropriate empty sequence message.
+Scenario 3: Single Job in the List
+Details:
+ TestName: singleJobInList
+ Description: Test the method with only one job in the list to ensure correct handling of this edge case.
+Execution:
+ Arrange: Create an ArrayList with a single Job object. Set size to 1.
+ Act: Call findJobSequence with the single-job ArrayList and size 1.
+ Assert: Verify the returned string contains only the ID of the single job.
+Validation:
+ Check if the method correctly processes a list with just one job, ensuring it doesn't require multiple jobs to function properly.
+Scenario 4: All Jobs with Same Deadline
+Details:
+ TestName: allJobsWithSameDeadline
+ Description: Test the method's behavior when all jobs have the same deadline.
+Execution:
+ Arrange: Create an ArrayList of Job objects, all with the same deadline. Set size appropriately.
+ Act: Call findJobSequence with this ArrayList and size.
+ Assert: Check if the returned sequence contains the correct number of jobs and is ordered by profit.
+Validation:
+ Verify that the method correctly prioritizes jobs based on profit when deadlines are identical, ensuring the highest-profit jobs are selected.
+Scenario 5: Jobs with Deadlines Exceeding Size
+Details:
+ TestName: jobsWithDeadlinesExceedingSize
+ Description: Test how the method handles jobs with deadlines greater than the given size parameter.
+Execution:
+ Arrange: Create an ArrayList of Job objects, some with deadlines exceeding the size parameter.
+ Act: Call findJobSequence with this ArrayList and a size smaller than some deadlines.
+ Assert: Verify that the returned sequence only includes jobs within the size limit and is correctly ordered.
+Validation:
+ Ensure the method correctly ignores or adjusts jobs with deadlines beyond the specified size, maintaining a valid sequence within the given constraints.
+Scenario 6: Maximum Possible Jobs
+Details:
+ TestName: maximumPossibleJobs
+ Description: Test the method with the maximum number of jobs that can fit in the given size.
+Execution:
+ Arrange: Create an ArrayList with 'size' number of Job objects, each with a unique deadline from 1 to size.
+ Act: Call findJobSequence with this ArrayList and the size.
+ Assert: Check if the returned sequence contains all job IDs in the correct order.
+Validation:
+ Verify that the method can handle and correctly sequence the maximum possible number of jobs, ensuring it scales appropriately to the given size.
+Scenario 7: Jobs with Zero Profit
+Details:
+ TestName: jobsWithZeroProfit
+ Description: Test how the method handles jobs with zero profit among other profitable jobs.
+Execution:
+ Arrange: Create an ArrayList of Job objects, including some with zero profit.
+ Act: Call findJobSequence with this ArrayList and an appropriate size.
+ Assert: Verify that the returned sequence prioritizes profitable jobs over zero-profit jobs.
+Validation:
+ Ensure the method correctly prioritizes jobs with positive profits over those with zero profit, reflecting a sensible job selection strategy.
+These test scenarios cover various aspects of the `findJobSequence` method, including normal operations, edge cases, and potential error conditions. They aim to validate the method's correctness, robustness, and adherence to the expected job sequencing logic.
+*/
+// ********RoostGPT********
+package com.thealgorithms.greedyalgorithms;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.*;
+
+@Tag("com.thealgorithms.datastructures.buffers")
+@Tag("com.thealgorithms.datastructures.buffers.get")
+@Tag("com.thealgorithms.datastructures.buffers.get")
+@Tag("com.thealgorithms.datastructures.lists")
+@Tag("com.thealgorithms.datastructures.lists.append")
+@Tag("com.thealgorithms.datastructures.lists.append")
+@Tag("com.thealgorithms.datastructures.lists.append")
+@Tag("com.thealgorithms.datastructures.lists.length")
+@Tag("com.thealgorithms.datastructures.lists.length")
+@Tag("com.thealgorithms.datastructures.stacks")
+@Tag("com.thealgorithms.datastructures.stacks.size")
+@Tag("com.thealgorithms.searches")
+@Tag("com.thealgorithms.searches.toString")
+@Tag("com.thealgorithms.greedyalgorithms")
+@Tag("com.thealgorithms.greedyalgorithms.findJobSequence")
+class JobSequencingFindJobSequenceTest {
+
+ @Test
+ void normalJobSequenceWithMultipleJobs() {
+ ArrayList jobs = new ArrayList<>(Arrays.asList(new Job('a', 2, 100), new Job('b', 1, 19),
+ new Job('c', 2, 27), new Job('d', 1, 25), new Job('e', 3, 15)));
+ String result = JobSequencing.findJobSequence(jobs, 3);
+ assertThat(result).isEqualTo("Job Sequence: c -> a -> e");
+ }
+
+ @Test
+ void emptyJobList() {
+ ArrayList jobs = new ArrayList<>();
+ String result = JobSequencing.findJobSequence(jobs, 0);
+ assertThat(result).isEqualTo("Job Sequence: ");
+ }
+
+ @Test
+ void singleJobInList() {
+ ArrayList jobs = new ArrayList<>(Arrays.asList(new Job('a', 1, 50)));
+ String result = JobSequencing.findJobSequence(jobs, 1);
+ assertThat(result).isEqualTo("Job Sequence: a");
+ }
+
+ @Test
+ void allJobsWithSameDeadline() {
+ ArrayList jobs = new ArrayList<>(Arrays.asList(new Job('a', 2, 100), new Job('b', 2, 19),
+ new Job('c', 2, 27), new Job('d', 2, 25), new Job('e', 2, 15)));
+ String result = JobSequencing.findJobSequence(jobs, 2);
+ assertThat(result).isEqualTo("Job Sequence: a -> c");
+ }
+
+ @Test
+ void jobsWithDeadlinesExceedingSize() {
+ ArrayList jobs = new ArrayList<>(Arrays.asList(new Job('a', 4, 100), new Job('b', 1, 19),
+ new Job('c', 3, 27), new Job('d', 2, 25), new Job('e', 5, 15)));
+ String result = JobSequencing.findJobSequence(jobs, 3);
+ assertThat(result).isEqualTo("Job Sequence: b -> d -> c");
+ }
+
+ @Test
+ void maximumPossibleJobs() {
+ ArrayList jobs = new ArrayList<>(Arrays.asList(new Job('a', 1, 100), new Job('b', 2, 19),
+ new Job('c', 3, 27), new Job('d', 4, 25), new Job('e', 5, 15)));
+ String result = JobSequencing.findJobSequence(jobs, 5);
+ assertThat(result).isEqualTo("Job Sequence: a -> b -> c -> d -> e");
+ }
+
+ @Test
+ void jobsWithZeroProfit() {
+ ArrayList jobs = new ArrayList<>(Arrays.asList(new Job('a', 2, 100), new Job('b', 1, 0),
+ new Job('c', 2, 27), new Job('d', 1, 25), new Job('e', 3, 0)));
+ String result = JobSequencing.findJobSequence(jobs, 3);
+ assertThat(result).isEqualTo("Job Sequence: d -> a -> c");
+ }
+
+ @ParameterizedTest
+ @MethodSource("provideTestCases")
+ void parameterizedTestCases(ArrayList jobs, int size, String expected) {
+ String result = JobSequencing.findJobSequence(jobs, size);
+ assertThat(result).isEqualTo(expected);
+ }
+
+ private static Stream provideTestCases() {
+ return Stream
+ .of(Arguments.of(new ArrayList<>(Arrays.asList(new Job('a', 2, 100), new Job('b', 1, 19),
+ new Job('c', 2, 27), new Job('d', 1, 25), new Job('e', 3, 15))), 3, "Job Sequence: c -> a -> e"),
+ Arguments.of(new ArrayList<>(), 0, "Job Sequence: "),
+ Arguments.of(new ArrayList<>(Arrays.asList(new Job('a', 1, 50))), 1, "Job Sequence: a"),
+ Arguments.of(new ArrayList<>(Arrays.asList(new Job('a', 2, 100), new Job('b', 2, 19),
+ new Job('c', 2, 27), new Job('d', 2, 25), new Job('e', 2, 15))), 2, "Job Sequence: a -> c"),
+ Arguments.of(
+ new ArrayList<>(Arrays.asList(new Job('a', 4, 100), new Job('b', 1, 19),
+ new Job('c', 3, 27), new Job('d', 2, 25), new Job('e', 5, 15))),
+ 3, "Job Sequence: b -> d -> c"),
+ Arguments.of(
+ new ArrayList<>(Arrays.asList(new Job('a', 1, 100), new Job('b', 2, 19),
+ new Job('c', 3, 27), new Job('d', 4, 25), new Job('e', 5, 15))),
+ 5, "Job Sequence: a -> b -> c -> d -> e"),
+ Arguments.of(new ArrayList<>(Arrays.asList(new Job('a', 2, 100), new Job('b', 1, 0),
+ new Job('c', 2, 27), new Job('d', 1, 25), new Job('e', 3, 0))), 3,
+ "Job Sequence: d -> a -> c"));
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessOfTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessOfTest.java
new file mode 100644
index 000000000000..10e98b8fb9e6
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessOfTest.java
@@ -0,0 +1,168 @@
+// ********RoostGPT********
+/*
+Test generated by RoostGPT for test java-algos using AI Type Claude AI and AI Model claude-3-5-sonnet-20240620
+ROOST_METHOD_HASH=of_eb8138c6bc
+ROOST_METHOD_SIG_HASH=of_7a04d5363c
+================================VULNERABILITIES================================
+Vulnerability: cwe-502: deserialization of untrusted data
+Issue: The 'of' method creates a Job object from input parameters without validation, potentially allowing untrusted data to be deserialized if used with external input.
+Solution: Implement input validation for all parameters before object creation. Use a builder pattern or factory method with proper checks.
+Vulnerability: cwe-134: uncontrolled format string
+Issue: The jobName parameter could contain format specifiers that might be interpreted if used in string formatting operations elsewhere in the code.
+Solution: Sanitize the jobName input to remove or escape any potential format specifiers before using it in string operations.
+Vulnerability: cwe-20: improper input validation
+Issue: The method lacks input validation for processingTime and deadline, which could lead to logical errors or unexpected behavior if invalid values are provided.
+Solution: Add input validation to ensure processingTime and deadline are positive integers and within acceptable ranges before object creation.
+================================================================================
+Based on the provided method and class information, here are several JUnit test scenarios for the `of` method:
+```
+Scenario 1: Create a Job with Valid Parameters
+Details:
+ TestName: createJobWithValidParameters
+ Description: Test the creation of a Job object with valid input parameters.
+Execution:
+ Arrange: Prepare valid input parameters for jobName, processingTime, and deadline.
+ Act: Call the of method with these parameters.
+ Assert: Verify that a non-null Job object is returned and its properties match the input.
+Validation:
+ This test ensures that the of method correctly creates a Job object when given valid inputs. It's crucial for verifying the basic functionality of the Job creation process.
+Scenario 2: Create a Job with Minimum Valid Values
+Details:
+ TestName: createJobWithMinimumValidValues
+ Description: Test the creation of a Job object with the minimum acceptable values for processingTime and deadline.
+Execution:
+ Arrange: Set up a jobName, and use 1 for both processingTime and deadline (assuming these are the minimum valid values).
+ Act: Invoke the of method with these parameters.
+ Assert: Check that a Job object is created with the specified minimum values.
+Validation:
+ This test verifies that the of method can handle edge cases with minimum valid inputs, ensuring robustness in Job creation.
+Scenario 3: Attempt to Create a Job with Null JobName
+Details:
+ TestName: createJobWithNullJobName
+ Description: Test the behavior of the of method when passed a null jobName.
+Execution:
+ Arrange: Prepare null for jobName, and valid values for processingTime and deadline.
+ Act: Call the of method with these parameters.
+ Assert: Expect an IllegalArgumentException or similar exception to be thrown.
+Validation:
+ This test ensures that the method properly handles invalid input for jobName, maintaining data integrity and preventing null values in critical fields.
+Scenario 4: Create a Job with Maximum Integer Values
+Details:
+ TestName: createJobWithMaxIntegerValues
+ Description: Test the creation of a Job with maximum possible integer values for processingTime and deadline.
+Execution:
+ Arrange: Set up a valid jobName and use Integer.MAX_VALUE for both processingTime and deadline.
+ Act: Call the of method with these parameters.
+ Assert: Verify that a Job object is created with the maximum values set correctly.
+Validation:
+ This test checks the method's ability to handle extreme values, ensuring it doesn't break under high-stress scenarios.
+Scenario 5: Attempt to Create a Job with Negative ProcessingTime
+Details:
+ TestName: createJobWithNegativeProcessingTime
+ Description: Test the of method's response to a negative value for processingTime.
+Execution:
+ Arrange: Prepare a valid jobName, a negative value for processingTime, and a valid deadline.
+ Act: Invoke the of method with these parameters.
+ Assert: Expect an IllegalArgumentException or similar exception to be thrown.
+Validation:
+ This test ensures that the method properly validates the processingTime parameter, rejecting invalid negative values.
+Scenario 6: Attempt to Create a Job with Negative Deadline
+Details:
+ TestName: createJobWithNegativeDeadline
+ Description: Test the of method's behavior when given a negative value for the deadline.
+Execution:
+ Arrange: Set up a valid jobName, a valid processingTime, and a negative value for deadline.
+ Act: Call the of method with these parameters.
+ Assert: Expect an IllegalArgumentException or similar exception to be thrown.
+Validation:
+ This test verifies that the method correctly handles invalid input for the deadline parameter, maintaining the integrity of the Job object.
+Scenario 7: Create a Job with Deadline Less Than ProcessingTime
+Details:
+ TestName: createJobWithDeadlineLessThanProcessingTime
+ Description: Test the creation of a Job where the deadline is earlier than the processing time.
+Execution:
+ Arrange: Prepare a valid jobName, set processingTime to a value greater than the deadline.
+ Act: Invoke the of method with these parameters.
+ Assert: Verify that a Job object is created and check if the lateness field is properly calculated.
+Validation:
+ This test ensures that the method can handle scenarios where jobs are inherently late, and verifies the correct calculation of the lateness field.
+```
+These scenarios cover various aspects of the `of` method, including normal operation, edge cases, and error handling. They aim to thoroughly test the method's functionality and robustness.
+*/
+// ********RoostGPT********
+package com.thealgorithms.greedyalgorithms;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import static org.junit.jupiter.api.Assertions.*;
+import java.util.Arrays;
+import org.junit.jupiter.api.*;
+
+@Tag("com.thealgorithms.greedyalgorithms")
+@Tag("com.thealgorithms.greedyalgorithms.of")
+class MinimizingLatenessOfTest {
+
+ @Test
+ void createJobWithValidParameters() {
+ Job job = Job.of("TestJob", 10, 20);
+ assertNotNull(job);
+ assertEquals("TestJob", job.jobName);
+ assertEquals(10, job.processingTime);
+ assertEquals(20, job.deadline);
+ }
+
+ @Test
+ void createJobWithMinimumValidValues() {
+ Job job = Job.of("MinJob", 1, 1);
+ assertNotNull(job);
+ assertEquals("MinJob", job.jobName);
+ assertEquals(1, job.processingTime);
+ assertEquals(1, job.deadline);
+ }
+
+ @Test
+ void createJobWithNullJobName() {
+ assertThrows(IllegalArgumentException.class, () -> Job.of(null, 10, 20));
+ }
+
+ @Test
+ void createJobWithMaxIntegerValues() {
+ Job job = Job.of("MaxJob", Integer.MAX_VALUE, Integer.MAX_VALUE);
+ assertNotNull(job);
+ assertEquals("MaxJob", job.jobName);
+ assertEquals(Integer.MAX_VALUE, job.processingTime);
+ assertEquals(Integer.MAX_VALUE, job.deadline);
+ }
+
+ @Test
+ void createJobWithNegativeProcessingTime() {
+ assertThrows(IllegalArgumentException.class, () -> Job.of("NegativeProcessing", -1, 20));
+ }
+
+ @Test
+ void createJobWithNegativeDeadline() {
+ assertThrows(IllegalArgumentException.class, () -> Job.of("NegativeDeadline", 10, -1));
+ }
+
+ @Test
+ void createJobWithDeadlineLessThanProcessingTime() {
+ Job job = Job.of("LateJob", 20, 10);
+ assertNotNull(job);
+ assertEquals("LateJob", job.jobName);
+ assertEquals(20, job.processingTime);
+ assertEquals(10, job.deadline);
+ assertTrue(job.lateness > 0);
+ }
+
+ @ParameterizedTest
+ @CsvSource({ "Job1, 5, 10", "Job2, 15, 20", "Job3, 30, 30" })
+ void createJobWithVariousParameters(String jobName, int processingTime, int deadline) {
+ Job job = Job.of(jobName, processingTime, deadline);
+ assertNotNull(job);
+ assertEquals(jobName, job.jobName);
+ assertEquals(processingTime, job.processingTime);
+ assertEquals(deadline, job.deadline);
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessToStringTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessToStringTest.java
new file mode 100644
index 000000000000..6686e85fa588
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessToStringTest.java
@@ -0,0 +1,197 @@
+// ********RoostGPT********
+/*
+Test generated by RoostGPT for test java-algos using AI Type Claude AI and AI Model claude-3-5-sonnet-20240620
+ROOST_METHOD_HASH=toString_7033209074
+ROOST_METHOD_SIG_HASH=toString_bbffdadaa2
+================================VULNERABILITIES================================
+Vulnerability: cwe-209: information exposure through an error message
+Issue: The toString() method may expose sensitive information about the job, such as processing times and lateness, which could be exploited if the output is logged or displayed to unauthorized users.
+Solution: Implement a separate method for logging or debugging that includes sensitive information, and use a more limited toString() method for general use. Consider using Java's built-in logging framework (java.util.logging) with appropriate log levels.
+Vulnerability: cwe-134: use of externally-controlled format string
+Issue: The use of String.format() with a hardcoded format string is generally safe, but if the format string were to come from an external source, it could lead to information disclosure or denial of service.
+Solution: Ensure that the format string is always hardcoded and not derived from any external input. If dynamic formatting is required, use StringBuilder or String concatenation instead of String.format().
+Vulnerability: cwe-581: object model violation: just one of equals and hashcode defined
+Issue: The toString() method is overridden, but there's no indication that equals() and hashCode() are also overridden. This can lead to unexpected behavior when using collections or comparing objects.
+Solution: Implement equals() and hashCode() methods along with toString(). Use IDE-generated implementations or consider using libraries like Lombok to automatically generate these methods.
+================================================================================
+Based on the provided method and class information, here are several JUnit test scenarios for the toString() method:
+Scenario 1: Normal Case with All Fields Set
+Details:
+ TestName: normalCaseAllFieldsSet
+ Description: Test the toString() method when all fields have valid values.
+Execution:
+ Arrange: Create a job object with all fields set (jobName, startTime, processingTime, lateness).
+ Act: Call the toString() method on the job object.
+ Assert: Verify that the returned string matches the expected format with all fields correctly represented.
+Validation:
+ This test ensures that the toString() method correctly formats all fields when they have valid values. It's crucial for verifying the basic functionality of the method.
+Scenario 2: Job with Zero Lateness
+Details:
+ TestName: jobWithZeroLateness
+ Description: Test the toString() method for a job that has no lateness.
+Execution:
+ Arrange: Create a job object with lateness set to 0.
+ Act: Call the toString() method on the job object.
+ Assert: Verify that the returned string includes "lateness: 0".
+Validation:
+ This test checks that the method correctly handles and displays zero lateness, which is a common scenario in job scheduling.
+Scenario 3: Job with Negative Lateness
+Details:
+ TestName: jobWithNegativeLateness
+ Description: Test the toString() method for a job that has negative lateness (finished early).
+Execution:
+ Arrange: Create a job object with a negative value for lateness.
+ Act: Call the toString() method on the job object.
+ Assert: Verify that the returned string correctly includes the negative lateness value.
+Validation:
+ This test ensures that the method can handle and display negative lateness values, which might occur if a job finishes before its deadline.
+Scenario 4: Job with Null Job Name
+Details:
+ TestName: jobWithNullJobName
+ Description: Test the toString() method when the jobName field is null.
+Execution:
+ Arrange: Create a job object with jobName set to null.
+ Act: Call the toString() method on the job object.
+ Assert: Verify that the method handles the null jobName gracefully, either by displaying "null" or an empty string for the name.
+Validation:
+ This test checks the method's robustness in handling null values for the jobName field, ensuring it doesn't throw a NullPointerException.
+Scenario 5: Job with Maximum Integer Values
+Details:
+ TestName: jobWithMaxIntegerValues
+ Description: Test the toString() method with maximum possible integer values for numeric fields.
+Execution:
+ Arrange: Create a job object with Integer.MAX_VALUE for startTime, processingTime, and lateness.
+ Act: Call the toString() method on the job object.
+ Assert: Verify that the method correctly formats and displays these large integer values.
+Validation:
+ This test ensures that the method can handle extreme values without overflow or formatting issues, which is important for edge cases in job scheduling.
+Scenario 6: Job with Minimum Integer Values
+Details:
+ TestName: jobWithMinIntegerValues
+ Description: Test the toString() method with minimum possible integer values for numeric fields.
+Execution:
+ Arrange: Create a job object with Integer.MIN_VALUE for startTime and lateness (processingTime should be non-negative).
+ Act: Call the toString() method on the job object.
+ Assert: Verify that the method correctly formats and displays these large negative integer values.
+Validation:
+ This test checks the method's ability to handle extreme negative values, ensuring proper formatting and display of such edge cases.
+Scenario 7: Job with Long Job Name
+Details:
+ TestName: jobWithLongJobName
+ Description: Test the toString() method with a very long job name.
+Execution:
+ Arrange: Create a job object with a very long string (e.g., 1000 characters) for jobName.
+ Act: Call the toString() method on the job object.
+ Assert: Verify that the method handles the long job name correctly without truncation or errors.
+Validation:
+ This test ensures that the method can handle unusually long job names without breaking the formatting or causing performance issues.
+These scenarios cover various aspects of the toString() method, including normal cases, edge cases, and potential error conditions. They aim to thoroughly test the method's functionality and robustness.
+*/
+// ********RoostGPT********
+package com.thealgorithms.greedyalgorithms;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.Arrays;
+import org.junit.jupiter.api.*;
+
+@Tag("com.thealgorithms.greedyalgorithms")
+@Tag("com.thealgorithms.greedyalgorithms.toString")
+class MinimizingLatenessToStringTest {
+
+ @Test
+ void normalCaseAllFieldsSet() {
+ Job job = new Job("Task1", 10, 20);
+ job.startTime = 5;
+ job.lateness = 2;
+
+ String result = job.toString();
+
+ assertThat(result).isEqualTo("Task1, startTime: 5, endTime: 15, lateness: 2");
+ }
+
+ @Test
+ void jobWithZeroLateness() {
+ Job job = new Job("Task2", 15, 30);
+ job.startTime = 10;
+ job.lateness = 0;
+
+ String result = job.toString();
+
+ assertThat(result).isEqualTo("Task2, startTime: 10, endTime: 25, lateness: 0");
+ }
+
+ @Test
+ void jobWithNegativeLateness() {
+ Job job = new Job("Task3", 5, 25);
+ job.startTime = 15;
+ job.lateness = -5;
+
+ String result = job.toString();
+
+ assertThat(result).isEqualTo("Task3, startTime: 15, endTime: 20, lateness: -5");
+ }
+
+ @Test
+ void jobWithNullJobName() {
+ Job job = new Job(null, 8, 15);
+ job.startTime = 3;
+ job.lateness = 1;
+
+ String result = job.toString();
+
+ assertThat(result).isEqualTo("null, startTime: 3, endTime: 11, lateness: 1");
+ }
+
+ @Test
+ void jobWithMaxIntegerValues() {
+ Job job = new Job("MaxTask", Integer.MAX_VALUE, Integer.MAX_VALUE);
+ job.startTime = Integer.MAX_VALUE;
+ job.lateness = Integer.MAX_VALUE;
+
+ String result = job.toString();
+
+ assertThat(result).isEqualTo("MaxTask, startTime: 2147483647, endTime: -2, lateness: 2147483647");
+ }
+
+ @Test
+ void jobWithMinIntegerValues() {
+ Job job = new Job("MinTask", 1, 1);
+ job.startTime = Integer.MIN_VALUE;
+ job.lateness = Integer.MIN_VALUE;
+
+ String result = job.toString();
+
+ assertThat(result).isEqualTo("MinTask, startTime: -2147483648, endTime: -2147483647, lateness: -2147483648");
+ }
+
+ @Test
+ void jobWithLongJobName() {
+ String longName = "a".repeat(1000);
+ Job job = new Job(longName, 5, 10);
+ job.startTime = 2;
+ job.lateness = 3;
+
+ String result = job.toString();
+
+ assertThat(result).startsWith(longName);
+ assertThat(result).endsWith(", startTime: 2, endTime: 7, lateness: 3");
+ }
+
+ @ParameterizedTest
+ @CsvSource({ "Task1, 5, 10, 15, 2", "Task2, 0, 20, 30, 0", "Task3, 10, 5, 25, -5" })
+ void parameterizedToStringTest(String jobName, int startTime, int processingTime, int deadline, int lateness) {
+ Job job = new Job(jobName, processingTime, deadline);
+ job.startTime = startTime;
+ job.lateness = lateness;
+
+ String result = job.toString();
+
+ String expected = String.format("%s, startTime: %d, endTime: %d, lateness: %d", jobName, startTime,
+ processingTime + startTime, lateness);
+ assertThat(result).isEqualTo(expected);
+ }
+
+}
\ No newline at end of file