-
Notifications
You must be signed in to change notification settings - Fork 20k
Greedy Algorithm Implementations and Explanations #4493 #4504
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 14 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
57a4701
Greedy Algorithm Implementations and Explanations #4493
Vineetttt 3405139
Greedy Algorithm Implementations and Explanations #4493
Vineetttt 0380598
Merge branch 'master' into master
Vineetttt 6d08ab2
modify dijkstras and adding JUnit Tests
Vineetttt 5c342ce
Merge branch 'master' of https://github.com/Vineetttt/TheAlgorithms-JAVA
Vineetttt 5205a48
modify activity selection and add JUnit Tests
Vineetttt e7c2fca
modify coinChange and add JUnit Tests
Vineetttt 4b99c75
modify fractionalKnapsack and add JUnit Tests
Vineetttt 249be4b
modify jobSequencing and add JUnit Tests
Vineetttt 4d53fc6
Merge branch 'master' into master
Vineetttt f41a78a
minor changes
Vineetttt 4963bf8
Merge branch 'master' of https://github.com/Vineetttt/TheAlgorithms-JAVA
Vineetttt 24d231c
minor change in JobSequecingTest
Vineetttt d57722a
minor change in JobSequencingTest
Vineetttt ebc6f47
clang format linter changes
Vineetttt ce0369b
clang format linter changes
Vineetttt 9844a39
removing dijkstra's algorithm
Vineetttt 7b2160b
adding partial coins test case
Vineetttt 38f20e9
removing print functions
Vineetttt 7ff6f01
linter job fixes
Vineetttt 8d89bf1
linter job fixes
Vineetttt 3cd77c6
minor changes for the clang linter job
Vineetttt 935aea1
Adding more JUnit Tests to the coin change problem
Vineetttt d68d840
Merge branch 'master' into master
Vineetttt ae8d56f
Merge branch 'master' into master
siriak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package com.thealgorithms.greedyalgorithms; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.Comparator; | ||
|
||
//Problem Link: https://en.wikipedia.org/wiki/Activity_selection_problem | ||
|
||
public class ActivitySelection { | ||
// Function to perform activity selection | ||
public static ArrayList<Integer> activitySelection(int start[], int end[]) { | ||
int n = start.length; | ||
int activities[][] = new int[n][3]; | ||
|
||
// Create a 2D array to store activities and their start/end times. | ||
// Each row: [activity index, start time, end time] | ||
|
||
for (int i = 0; i < n; i++) { | ||
activities[i][0] = i; // Assign activity index | ||
activities[i][1] = start[i]; // Assign start time | ||
activities[i][2] = end[i]; // Assign end time | ||
} | ||
|
||
// Sort activities by their end times in ascending order. | ||
Arrays.sort(activities, Comparator.comparingDouble(o -> o[2])); | ||
|
||
int max = 1; | ||
int lastEnd; | ||
ArrayList<Integer> ans = new ArrayList<>(); | ||
|
||
ans.add(activities[0][0]); | ||
lastEnd = activities[0][2]; | ||
|
||
// Iterate through sorted activities to select compatible ones. | ||
for (int i = 1; i < n; i++) { | ||
if (activities[i][1] >= lastEnd) { | ||
max++; | ||
ans.add(activities[i][0]); | ||
lastEnd = activities[i][2]; | ||
} | ||
} | ||
return ans; | ||
} | ||
public static void printActivities(ArrayList<Integer> ans){ | ||
// Print the selected activities. | ||
System.out.print("Following activities are selected : \n"); | ||
for (int i = 0; i < ans.size(); i++) { | ||
System.out.print("A" + ans.get(i) + " "); | ||
} | ||
System.out.println(); | ||
} | ||
} |
47 changes: 47 additions & 0 deletions
47
src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package com.thealgorithms.greedyalgorithms; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.Comparator; | ||
|
||
//Problem Link : https://en.wikipedia.org/wiki/Change-making_problem | ||
|
||
public class CoinChange { | ||
// Function to solve the coin change problem | ||
public static ArrayList<Integer> coinChangeProblem(int amount) { | ||
// Define an array of coin denominations in descending order | ||
Integer coins[] = {1, 2, 5, 10, 20, 50, 100, 500, 2000}; | ||
|
||
// Sort the coin denominations in descending order | ||
Arrays.sort(coins, Comparator.reverseOrder()); | ||
|
||
int count = 0; // Variable to keep track of the total number of coins used | ||
ArrayList<Integer> ans = new ArrayList<>(); // List to store selected coins | ||
|
||
// Iterate through the coin denominations | ||
for (int i = 0; i < coins.length; i++) { | ||
// Check if the current coin denomination can be used to reduce the remaining amount | ||
if (coins[i] <= amount) { | ||
// Repeatedly subtract the coin denomination from the remaining amount | ||
while (coins[i] <= amount) { | ||
count++; // Increment the count of coins used | ||
ans.add(coins[i]); // Add the coin to the list of selected coins | ||
amount -= coins[i]; // Update the remaining amount | ||
} | ||
} | ||
} | ||
return ans; | ||
} | ||
public static void printCoins(ArrayList<Integer> ans){ | ||
// Print the selected coins | ||
System.out.println("Coins: "); | ||
for (int i = 0; i < ans.size(); i++) { | ||
System.out.print(ans.get(i) + " "); | ||
} | ||
} | ||
|
||
public static void main(String args[]) { | ||
// Call the coinChangeProblem function with the given amount (591) | ||
System.out.println(coinChangeProblem(3)); | ||
} | ||
} |
71 changes: 71 additions & 0 deletions
71
src/main/java/com/thealgorithms/greedyalgorithms/DijkstrasAlgorithm.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package com.thealgorithms.greedyalgorithms; | ||
|
||
import java.util.PriorityQueue; | ||
|
||
// Link: https://en.wikipedia.org/wiki/Dijkstra's_algorithm | ||
|
||
public class DijkstrasAlgorithm { | ||
|
||
static class Pair implements Comparable<Pair> { | ||
int n; | ||
int path; | ||
|
||
public Pair(int n, int path) { | ||
this.n = n; | ||
this.path = path; | ||
} | ||
|
||
@Override | ||
public int compareTo(Pair p2) { | ||
return this.path - p2.path; | ||
} | ||
} | ||
|
||
// Function to perform Dijkstra's algorithm to find shortest paths | ||
public static int[] dijkstra(int[][] graph, int src) { | ||
int n = graph.length; | ||
int[] dist = new int[n]; | ||
|
||
// Initialize distances to all nodes as infinity except the source node | ||
for (int i = 0; i < n; i++) { | ||
if (i != src) { | ||
dist[i] = Integer.MAX_VALUE; | ||
} | ||
} | ||
|
||
boolean[] vis = new boolean[n]; | ||
PriorityQueue<Pair> pq = new PriorityQueue<>(); | ||
pq.add(new Pair(src, 0)); | ||
|
||
while (!pq.isEmpty()) { | ||
Pair curr = pq.remove(); | ||
|
||
// Mark the current node as visited | ||
if (!vis[curr.n]) { | ||
vis[curr.n] = true; | ||
|
||
// Explore neighbors of the current node | ||
for (int v = 0; v < n; v++) { | ||
if (graph[curr.n][v] != 0) { // Check if there is an edge | ||
int wt = graph[curr.n][v]; | ||
|
||
// Relaxation step: Update the distance if a shorter path is found | ||
if (dist[curr.n] != Integer.MAX_VALUE && dist[curr.n] + wt < dist[v]) { | ||
dist[v] = dist[curr.n] + wt; | ||
pq.add(new Pair(v, dist[v])); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
return dist; | ||
} | ||
|
||
public static void printShortestDistance(int[] dist) { | ||
for (int i = 0; i < dist.length; i++) { | ||
System.out.print(dist[i] + " "); | ||
} | ||
System.out.println(); | ||
} | ||
} |
42 changes: 42 additions & 0 deletions
42
src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package com.thealgorithms.greedyalgorithms; | ||
|
||
import java.util.Arrays; | ||
import java.util.Comparator; | ||
|
||
//Problem Link: https://en.wikipedia.org/wiki/Continuous_knapsack_problem | ||
|
||
public class FractionalKnapsack { | ||
// Function to perform fractional knapsack | ||
public static int fractionalKnapsack(int weight[], int value[], int capacity) { | ||
// Create a 2D array to store item indices and their value-to-weight ratios. | ||
double ratio[][] = new double[weight.length][2]; | ||
|
||
// Populate the ratio array with item indices and their value-to-weight ratios. | ||
for (int i = 0; i < weight.length; i++) { | ||
ratio[i][0] = i; // Assign item index. | ||
ratio[i][1] = value[i] / (double) weight[i]; // Calculate and assign value-to-weight ratio. | ||
} | ||
|
||
// Sort items by their value-to-weight ratios in descending order. | ||
Arrays.sort(ratio, Comparator.comparingDouble(o -> o[1])); | ||
|
||
int finalValue = 0; // Variable to store the final knapsack value. | ||
double current = capacity; // Variable to track the remaining capacity of the knapsack. | ||
|
||
// Iterate through the sorted items to select items for the knapsack. | ||
for (int i = ratio.length - 1; i >= 0; i--) { | ||
int index = (int) ratio[i][0]; // Get the item index. | ||
|
||
if (current >= weight[index]) { | ||
// If the entire item can fit in the knapsack, add its value. | ||
finalValue += value[index]; | ||
current -= weight[index]; | ||
} else { | ||
// If only a fraction of the item can fit, add a proportionate value. | ||
finalValue += ratio[i][1] * current; | ||
break; // Stop adding items to the knapsack since it's full. | ||
} | ||
} | ||
return finalValue; | ||
} | ||
} |
65 changes: 65 additions & 0 deletions
65
src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package com.thealgorithms.greedyalgorithms; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.Collections; | ||
|
||
//Problem Link: https://en.wikipedia.org/wiki/Job-shop_scheduling | ||
|
||
public class JobSequencing { | ||
|
||
// Define a Job class that implements Comparable for sorting by profit in descending order | ||
static class Job implements Comparable<Job> { | ||
char id; | ||
int deadline; | ||
int profit; | ||
|
||
// Compare jobs by profit in descending order | ||
@Override | ||
public int compareTo(Job otherJob) { | ||
return otherJob.profit - this.profit; | ||
} | ||
|
||
public Job(char id, int deadline, int profit) { | ||
this.id = id; | ||
this.deadline = deadline; | ||
this.profit = profit; | ||
} | ||
} | ||
|
||
// Function to print the job sequence | ||
public static String findJobSequence(ArrayList<Job> jobs, int size) { | ||
Boolean[] slots = new Boolean[size]; | ||
Arrays.fill(slots, false); | ||
|
||
int result[] = new int[size]; | ||
|
||
// Iterate through jobs to find the optimal job sequence | ||
for (int i = 0; i < size; i++) { | ||
for (int j = jobs.get(i).deadline - 1; j >= 0; j--) { | ||
if (!slots[j]) { | ||
result[j] = i; | ||
slots[j] = true; | ||
break; | ||
} | ||
} | ||
} | ||
|
||
// Create a StringBuilder to build the job sequence string | ||
StringBuilder jobSequenceBuilder = new StringBuilder(); | ||
jobSequenceBuilder.append("Job Sequence: "); | ||
for (int i = 0; i < jobs.size(); i++) { | ||
if (slots[i]) { | ||
jobSequenceBuilder.append(jobs.get(result[i]).id).append(" -> "); | ||
} | ||
} | ||
|
||
// Remove the trailing " -> " from the job sequence | ||
if (jobSequenceBuilder.length() >= 4) { | ||
jobSequenceBuilder.setLength(jobSequenceBuilder.length() - 4); | ||
} | ||
|
||
// Return the job sequence as a string | ||
return jobSequenceBuilder.toString(); | ||
} | ||
} |
42 changes: 42 additions & 0 deletions
42
src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package com.thealgorithms.greedyalgorithms; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import static org.junit.jupiter.api.Assertions.*; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
|
||
public class ActivitySelectionTest { | ||
@Test | ||
public void testActivitySelection() { | ||
int start[] = {1, 3, 0, 5, 8, 5}; | ||
int end[] = {2, 4, 6, 7, 9, 9}; | ||
|
||
ArrayList<Integer> result = ActivitySelection.activitySelection(start, end); | ||
ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(0, 1, 3, 4)); | ||
|
||
assertEquals(expected, result); | ||
} | ||
|
||
@Test | ||
public void testSingleActivity() { | ||
int start[] = {1}; | ||
int end[] = {2}; | ||
|
||
ArrayList<Integer> result = ActivitySelection.activitySelection(start, end); | ||
ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(0)); | ||
|
||
assertEquals(expected, result); | ||
} | ||
|
||
@Test | ||
public void testNoOverlap() { | ||
int start[] = {1, 2, 3}; | ||
int end[] = {2, 3, 4}; | ||
|
||
ArrayList<Integer> result = ActivitySelection.activitySelection(start, end); | ||
ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(0, 1, 2)); | ||
|
||
assertEquals(expected, result); | ||
} | ||
} |
31 changes: 31 additions & 0 deletions
31
src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package com.thealgorithms.greedyalgorithms; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
|
||
public class CoinChangeTest { | ||
@Test | ||
public void testCoinChangeProblemWithValidAmount() { | ||
ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(500, 50, 20, 20, 1)); | ||
ArrayList<Integer> coins = CoinChange.coinChangeProblem(591); | ||
assertEquals(expected, coins); | ||
} | ||
|
||
@Test | ||
public void testCoinChangeProblemWithLargeAmount() { | ||
ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(2000)); | ||
ArrayList<Integer> coins = CoinChange.coinChangeProblem(2000); | ||
assertEquals(expected, coins); | ||
} | ||
|
||
@Test | ||
public void testCoinChangeProblemWithSmallAmount() { | ||
ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(2,1)); | ||
ArrayList<Integer> coins = CoinChange.coinChangeProblem(3); | ||
assertEquals(expected, coins); | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.