Skip to content

Commit 7ae1ece

Browse files
authored
Merge branch 'master' into dependabot/maven/org.mockito-mockito-core-5.14.2
2 parents 6b2c5f4 + 33dee07 commit 7ae1ece

File tree

8 files changed

+290
-15
lines changed

8 files changed

+290
-15
lines changed

DIRECTORY.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@
262262
* [TilingProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/divideandconquer/TilingProblem.java)
263263
* dynamicprogramming
264264
* [Abbreviation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/Abbreviation.java)
265+
* [AssignmentUsingBitmask](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmask.java)
265266
* [BoardPath](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java)
266267
* [BoundaryFill](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java)
267268
* [BruteForceKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java)
@@ -320,6 +321,8 @@
320321
* [JobSequencing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java)
321322
* [MergeIntervals](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java)
322323
* [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java)
324+
* [MinimumWaitingTime](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTime.java)
325+
* [StockProfitCalculator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/StockProfitCalculator.java)
323326
* io
324327
* [BufferedReader](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/io/BufferedReader.java)
325328
* lineclipping
@@ -864,6 +867,7 @@
864867
* [TilingProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/divideandconquer/TilingProblemTest.java)
865868
* dynamicprogramming
866869
* [AbbreviationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/AbbreviationTest.java)
870+
* [AssignmentUsingBitmaskTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmaskTest.java)
867871
* [BoardPathTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/BoardPathTest.java)
868872
* [BoundaryFillTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/BoundaryFillTest.java)
869873
* [BruteForceKnapsackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsackTest.java)
@@ -920,6 +924,8 @@
920924
* [JobSequencingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java)
921925
* [MergeIntervalsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MergeIntervalsTest.java)
922926
* [MinimizingLatenessTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessTest.java)
927+
* [MinimumWaitingTimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTimeTest.java)
928+
* [StockProfitCalculatorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java)
923929
* io
924930
* [BufferedReaderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/io/BufferedReaderTest.java)
925931
* lineclipping
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
/**
8+
* The AssignmentUsingBitmask class is used to calculate the total number of ways
9+
* tasks can be distributed among people, given specific constraints on who can perform which tasks.
10+
* The approach uses bitmasking and dynamic programming to efficiently solve the problem.
11+
*
12+
* @author Hardvan
13+
*/
14+
public final class AssignmentUsingBitmask {
15+
16+
private final int totalTasks;
17+
private final int[][] dp;
18+
private final List<List<Integer>> task;
19+
private final int finalMask;
20+
21+
/**
22+
* Constructor for the AssignmentUsingBitmask class.
23+
*
24+
* @param taskPerformed a list of lists, where each inner list contains the tasks that a person can perform.
25+
* @param total the total number of tasks.
26+
*/
27+
public AssignmentUsingBitmask(List<List<Integer>> taskPerformed, int total) {
28+
this.totalTasks = total;
29+
this.dp = new int[1 << taskPerformed.size()][total + 1];
30+
for (int[] row : dp) {
31+
Arrays.fill(row, -1);
32+
}
33+
34+
this.task = new ArrayList<>(totalTasks + 1);
35+
for (int i = 0; i <= totalTasks; i++) {
36+
this.task.add(new ArrayList<>());
37+
}
38+
39+
// Final mask to check if all persons are included
40+
this.finalMask = (1 << taskPerformed.size()) - 1;
41+
42+
// Fill the task list
43+
for (int i = 0; i < taskPerformed.size(); i++) {
44+
for (int j : taskPerformed.get(i)) {
45+
this.task.get(j).add(i);
46+
}
47+
}
48+
}
49+
50+
/**
51+
* Counts the ways to assign tasks until the given task number with the specified mask.
52+
*
53+
* @param mask the bitmask representing the current state of assignments.
54+
* @param taskNo the current task number being processed.
55+
* @return the number of ways to assign tasks.
56+
*/
57+
private int countWaysUntil(int mask, int taskNo) {
58+
if (mask == finalMask) {
59+
return 1;
60+
}
61+
if (taskNo > totalTasks) {
62+
return 0;
63+
}
64+
if (dp[mask][taskNo] != -1) {
65+
return dp[mask][taskNo];
66+
}
67+
68+
int totalWays = countWaysUntil(mask, taskNo + 1);
69+
70+
// Assign tasks to all possible persons
71+
for (int p : task.get(taskNo)) {
72+
// If the person is already assigned a task
73+
if ((mask & (1 << p)) != 0) {
74+
continue;
75+
}
76+
totalWays += countWaysUntil(mask | (1 << p), taskNo + 1);
77+
}
78+
79+
dp[mask][taskNo] = totalWays;
80+
return dp[mask][taskNo];
81+
}
82+
83+
/**
84+
* Counts the total number of ways to distribute tasks among persons.
85+
*
86+
* @return the total number of ways to distribute tasks.
87+
*/
88+
public int countNoOfWays() {
89+
return countWaysUntil(0, 1);
90+
}
91+
}

src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,50 @@
33
import java.util.Arrays;
44
import java.util.Comparator;
55

6-
// Problem Link: https://en.wikipedia.org/wiki/Continuous_knapsack_problem
7-
6+
/**
7+
* The FractionalKnapsack class provides a method to solve the fractional knapsack problem
8+
* using a greedy algorithm approach. It allows for selecting fractions of items to maximize
9+
* the total value in a knapsack with a given weight capacity.
10+
*
11+
* The problem consists of a set of items, each with a weight and a value, and a knapsack
12+
* that can carry a maximum weight. The goal is to maximize the value of items in the knapsack,
13+
* allowing for the inclusion of fractions of items.
14+
*
15+
* Problem Link: https://en.wikipedia.org/wiki/Continuous_knapsack_problem
16+
*/
817
public final class FractionalKnapsack {
918
private FractionalKnapsack() {
1019
}
11-
// Function to perform fractional knapsack
20+
21+
/**
22+
* Computes the maximum value that can be accommodated in a knapsack of a given capacity.
23+
*
24+
* @param weight an array of integers representing the weights of the items
25+
* @param value an array of integers representing the values of the items
26+
* @param capacity an integer representing the maximum weight capacity of the knapsack
27+
* @return the maximum value that can be obtained by including the items in the knapsack
28+
*/
1229
public static int fractionalKnapsack(int[] weight, int[] value, int capacity) {
13-
// Create a 2D array to store item indices and their value-to-weight ratios.
1430
double[][] ratio = new double[weight.length][2];
1531

16-
// Populate the ratio array with item indices and their value-to-weight ratios.
1732
for (int i = 0; i < weight.length; i++) {
18-
ratio[i][0] = i; // Assign item index.
19-
ratio[i][1] = value[i] / (double) weight[i]; // Calculate and assign value-to-weight ratio.
33+
ratio[i][0] = i;
34+
ratio[i][1] = value[i] / (double) weight[i];
2035
}
2136

22-
// Sort items by their value-to-weight ratios in descending order.
2337
Arrays.sort(ratio, Comparator.comparingDouble(o -> o[1]));
2438

25-
int finalValue = 0; // Variable to store the final knapsack value.
26-
double current = capacity; // Variable to track the remaining capacity of the knapsack.
39+
int finalValue = 0;
40+
double current = capacity;
2741

28-
// Iterate through the sorted items to select items for the knapsack.
2942
for (int i = ratio.length - 1; i >= 0; i--) {
30-
int index = (int) ratio[i][0]; // Get the item index.
43+
int index = (int) ratio[i][0];
3144
if (current >= weight[index]) {
32-
// If the entire item can fit in the knapsack, add its value.
3345
finalValue += value[index];
3446
current -= weight[index];
3547
} else {
36-
// If only a fraction of the item can fit, add a proportionate value.
3748
finalValue += (int) (ratio[i][1] * current);
38-
break; // Stop adding items to the knapsack since it's full.
49+
break;
3950
}
4051
}
4152
return finalValue;
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* The MinimumWaitingTime class provides a method to calculate the minimum
7+
* waiting time for a list of queries using a greedy algorithm.
8+
*
9+
* @author Hardvan
10+
*/
11+
public final class MinimumWaitingTime {
12+
private MinimumWaitingTime() {
13+
}
14+
15+
/**
16+
* Calculates the minimum waiting time for a list of queries.
17+
* The function sorts the queries in non-decreasing order and then calculates
18+
* the waiting time for each query based on its position in the sorted list.
19+
*
20+
* @param queries an array of integers representing the query times in picoseconds
21+
* @return the minimum waiting time in picoseconds
22+
*/
23+
public static int minimumWaitingTime(int[] queries) {
24+
int n = queries.length;
25+
if (n <= 1) {
26+
return 0;
27+
}
28+
29+
Arrays.sort(queries);
30+
31+
int totalWaitingTime = 0;
32+
for (int i = 0; i < n; i++) {
33+
totalWaitingTime += queries[i] * (n - i - 1);
34+
}
35+
return totalWaitingTime;
36+
}
37+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
/**
4+
* The StockProfitCalculator class provides a method to calculate the maximum profit
5+
* that can be made from a single buy and sell of one share of stock.
6+
* The approach uses a greedy algorithm to efficiently determine the maximum profit.
7+
*
8+
* @author Hardvan
9+
*/
10+
public final class StockProfitCalculator {
11+
private StockProfitCalculator() {
12+
}
13+
14+
/**
15+
* Calculates the maximum profit from a list of stock prices.
16+
*
17+
* @param prices an array of integers representing the stock prices on different days
18+
* @return the maximum profit that can be achieved from a single buy and sell
19+
* transaction, or 0 if no profit can be made
20+
*/
21+
public static int maxProfit(int[] prices) {
22+
if (prices == null || prices.length == 0) {
23+
return 0;
24+
}
25+
26+
int minPrice = prices[0];
27+
int maxProfit = 0;
28+
for (int price : prices) {
29+
minPrice = Math.min(price, minPrice);
30+
maxProfit = Math.max(price - minPrice, maxProfit);
31+
}
32+
return maxProfit;
33+
}
34+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.Arrays;
6+
import java.util.List;
7+
import org.junit.jupiter.api.Test;
8+
9+
public final class AssignmentUsingBitmaskTest {
10+
11+
@Test
12+
public void testCountNoOfWays() {
13+
int totalTasks = 5;
14+
15+
List<List<Integer>> taskPerformed = Arrays.asList(Arrays.asList(1, 3, 4), Arrays.asList(1, 2, 5), Arrays.asList(3, 4));
16+
17+
AssignmentUsingBitmask assignment = new AssignmentUsingBitmask(taskPerformed, totalTasks);
18+
int ways = assignment.countNoOfWays();
19+
assertEquals(10, ways);
20+
}
21+
22+
@Test
23+
public void testNoPossibleAssignments() {
24+
int totalTasks = 3;
25+
26+
List<List<Integer>> taskPerformed = Arrays.asList(Arrays.asList(2), Arrays.asList(3));
27+
28+
AssignmentUsingBitmask assignment = new AssignmentUsingBitmask(taskPerformed, totalTasks);
29+
int ways = assignment.countNoOfWays();
30+
assertEquals(1, ways);
31+
}
32+
33+
@Test
34+
public void testSinglePersonMultipleTasks() {
35+
int totalTasks = 3;
36+
37+
List<List<Integer>> taskPerformed = Arrays.asList(Arrays.asList(1, 2, 3));
38+
39+
AssignmentUsingBitmask assignment = new AssignmentUsingBitmask(taskPerformed, totalTasks);
40+
int ways = assignment.countNoOfWays();
41+
assertEquals(3, ways);
42+
}
43+
44+
@Test
45+
public void testMultiplePeopleSingleTask() {
46+
int totalTasks = 1;
47+
48+
List<List<Integer>> taskPerformed = Arrays.asList(Arrays.asList(1), Arrays.asList(1));
49+
50+
AssignmentUsingBitmask assignment = new AssignmentUsingBitmask(taskPerformed, totalTasks);
51+
int ways = assignment.countNoOfWays();
52+
assertEquals(0, ways);
53+
}
54+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.stream.Stream;
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.Arguments;
8+
import org.junit.jupiter.params.provider.MethodSource;
9+
10+
public class MinimumWaitingTimeTest {
11+
12+
@ParameterizedTest
13+
@MethodSource("provideTestCases")
14+
public void testMinimumWaitingTime(int[] queries, int expected) {
15+
assertEquals(expected, MinimumWaitingTime.minimumWaitingTime(queries));
16+
}
17+
18+
private static Stream<Arguments> provideTestCases() {
19+
return Stream.of(Arguments.of(new int[] {3, 2, 1, 2, 6}, 17), Arguments.of(new int[] {3, 2, 1}, 4), Arguments.of(new int[] {1, 2, 3, 4}, 10), Arguments.of(new int[] {5, 5, 5, 5}, 30), Arguments.of(new int[] {}, 0));
20+
}
21+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.stream.Stream;
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.Arguments;
8+
import org.junit.jupiter.params.provider.MethodSource;
9+
10+
public class StockProfitCalculatorTest {
11+
12+
@ParameterizedTest
13+
@MethodSource("provideTestCases")
14+
public void testMaxProfit(int[] prices, int expected) {
15+
assertEquals(expected, StockProfitCalculator.maxProfit(prices));
16+
}
17+
18+
private static Stream<Arguments> provideTestCases() {
19+
return Stream.of(Arguments.of(new int[] {7, 1, 5, 3, 6, 4}, 5), Arguments.of(new int[] {7, 6, 4, 3, 1}, 0), Arguments.of(new int[] {5, 5, 5, 5, 5}, 0), Arguments.of(new int[] {10}, 0), Arguments.of(new int[] {1, 5}, 4), Arguments.of(new int[] {2, 4, 1, 3, 7, 5}, 6));
20+
}
21+
}

0 commit comments

Comments
 (0)