Skip to content

Commit 09ce90f

Browse files
authored
Merge branch 'master' into climbing_stais_improvement
2 parents d848b73 + e6f597a commit 09ce90f

File tree

6 files changed

+228
-43
lines changed

6 files changed

+228
-43
lines changed

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@
265265
* [ActivitySelection](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java)
266266
* [CoinChange](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java)
267267
* [FractionalKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java)
268+
* [GaleShapley](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java)
268269
* [JobSequencing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java)
269270
* [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java)
270271
* io
@@ -749,6 +750,7 @@
749750
* [ActivitySelectionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java)
750751
* [CoinChangeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java)
751752
* [FractionalKnapsackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java)
753+
* [GaleShapleyTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java)
752754
* [JobSequencingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java)
753755
* [MinimizingLatenessTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessTest.java)
754756
* io

src/main/java/com/thealgorithms/backtracking/MColoring.java

Lines changed: 43 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,71 +7,90 @@
77
import java.util.Set;
88

99
/**
10+
* Node class represents a graph node. Each node is associated with a color
11+
* (initially 1) and contains a set of edges representing its adjacent nodes.
12+
*
1013
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
1114
*/
1215
class Node {
13-
int color = 1;
14-
Set<Integer> edges = new HashSet<Integer>();
16+
int color = 1; // Initial color for each node
17+
Set<Integer> edges = new HashSet<Integer>(); // Set of edges representing adjacent nodes
1518
}
1619

20+
/**
21+
* MColoring class solves the M-Coloring problem where the goal is to determine
22+
* if it's possible to color a graph using at most M colors such that no two
23+
* adjacent nodes have the same color.
24+
*/
1725
public final class MColoring {
26+
1827
private MColoring() {
19-
}
20-
static int possiblePaint(ArrayList<Node> nodes, int n, int m) {
28+
} // Prevent instantiation of utility class
2129

22-
// Create a visited array of n nodes
30+
/**
31+
* Determines whether it is possible to color the graph using at most M colors.
32+
*
33+
* @param nodes List of nodes representing the graph.
34+
* @param n The total number of nodes in the graph.
35+
* @param m The maximum number of allowed colors.
36+
* @return true if the graph can be colored using M colors, false otherwise.
37+
*/
38+
static boolean isColoringPossible(ArrayList<Node> nodes, int n, int m) {
39+
40+
// Visited array keeps track of whether each node has been processed.
2341
ArrayList<Integer> visited = new ArrayList<Integer>();
2442
for (int i = 0; i < n + 1; i++) {
25-
visited.add(0);
43+
visited.add(0); // Initialize all nodes as unvisited (0)
2644
}
2745

28-
// maxColors used till now are 1 as
29-
// all nodes are painted color 1
46+
// The number of colors used so far (initially set to 1, since all nodes
47+
// start with color 1).
3048
int maxColors = 1;
3149

50+
// Loop through all the nodes to ensure every node is visited, in case the
51+
// graph is disconnected.
3252
for (int sv = 1; sv <= n; sv++) {
3353
if (visited.get(sv) > 0) {
34-
continue;
54+
continue; // Skip nodes that are already visited
3555
}
3656

37-
// If the starting point is unvisited,
38-
// mark it visited and push it in queue
57+
// If the node is unvisited, mark it as visited and add it to the queue for BFS.
3958
visited.set(sv, 1);
4059
Queue<Integer> q = new LinkedList<>();
4160
q.add(sv);
4261

43-
// BFS
62+
// Perform BFS to process all nodes and their adjacent nodes
4463
while (q.size() != 0) {
45-
int top = q.peek();
64+
int top = q.peek(); // Get the current node from the queue
4665
q.remove();
4766

48-
// Checking all adjacent nodes
49-
// to "top" edge in our queue
67+
// Check all adjacent nodes of the current node
5068
for (int it : nodes.get(top).edges) {
5169

52-
// If the color of the
53-
// adjacent node is same, increase it by
54-
// 1
70+
// If the adjacent node has the same color as the current node, increment its
71+
// color to avoid conflict.
5572
if (nodes.get(top).color == nodes.get(it).color) {
5673
nodes.get(it).color += 1;
5774
}
5875

59-
// If number of colors used exceeds m,
60-
// return 0
76+
// Keep track of the maximum number of colors used so far
6177
maxColors = Math.max(maxColors, Math.max(nodes.get(top).color, nodes.get(it).color));
78+
79+
// If the number of colors used exceeds the allowed limit M, return false.
6280
if (maxColors > m) {
63-
return 0;
81+
return false;
6482
}
6583

66-
// If the adjacent node is not visited,
67-
// mark it visited and push it in queue
84+
// If the adjacent node hasn't been visited yet, mark it as visited and add it
85+
// to the queue for further processing.
6886
if (visited.get(it) == 0) {
6987
visited.set(it, 1);
7088
q.add(it);
7189
}
7290
}
7391
}
7492
}
75-
return 1;
93+
94+
return true; // Possible to color the entire graph with M or fewer colors.
7695
}
7796
}

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

Lines changed: 41 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,39 +4,65 @@
44
import java.util.Arrays;
55
import java.util.Comparator;
66

7-
// Problem Link: https://en.wikipedia.org/wiki/Activity_selection_problem
7+
// Problem Link: https://en.wikipedia.org/wiki/Activity_selection_problem
88

99
public final class ActivitySelection {
10+
11+
// Private constructor to prevent instantiation of the utility class
1012
private ActivitySelection() {
1113
}
12-
// Function to perform activity selection
14+
15+
/**
16+
* Function to perform activity selection using a greedy approach.
17+
*
18+
* The goal is to select the maximum number of activities that don't overlap
19+
* with each other, based on their start and end times. Activities are chosen
20+
* such that no two selected activities overlap.
21+
*
22+
* @param startTimes Array containing the start times of the activities.
23+
* @param endTimes Array containing the end times of the activities.
24+
* @return A list of indices representing the selected activities that can be
25+
* performed without overlap.
26+
*/
1327
public static ArrayList<Integer> activitySelection(int[] startTimes, int[] endTimes) {
1428
int n = startTimes.length;
15-
int[][] activities = new int[n][3];
1629

17-
// Create a 2D array to store activities and their start/end times.
18-
// Each row: [activity index, start time, end time]
30+
// Create a 2D array to store activity indices along with their start and end
31+
// times.
32+
// Each row represents an activity in the format: [activity index, start time,
33+
// end time].
34+
int[][] activities = new int[n][3];
1935

36+
// Populate the 2D array with the activity index, start time, and end time.
2037
for (int i = 0; i < n; i++) {
21-
activities[i][0] = i; // Assign activity index
22-
activities[i][1] = startTimes[i]; // Assign start time
23-
activities[i][2] = endTimes[i]; // Assign end time
38+
activities[i][0] = i; // Assign the activity index
39+
activities[i][1] = startTimes[i]; // Assign the start time of the activity
40+
activities[i][2] = endTimes[i]; // Assign the end time of the activity
2441
}
2542

26-
// Sort activities by their end times in ascending order.
43+
// Sort activities based on their end times in ascending order.
44+
// This ensures that we always try to finish earlier activities first.
2745
Arrays.sort(activities, Comparator.comparingDouble(activity -> activity[2]));
28-
int lastEndTime;
46+
int lastEndTime; // Variable to store the end time of the last selected activity
47+
// List to store the indices of selected activities
2948
ArrayList<Integer> selectedActivities = new ArrayList<>();
30-
selectedActivities.add(activities[0][0]);
31-
lastEndTime = activities[0][2];
3249

33-
// Iterate through sorted activities to select compatible ones.
50+
// Select the first activity (as it has the earliest end time after sorting)
51+
selectedActivities.add(activities[0][0]); // Add the first activity index to the result
52+
lastEndTime = activities[0][2]; // Keep track of the end time of the last selected activity
53+
54+
// Iterate over the sorted activities to select the maximum number of compatible
55+
// activities.
3456
for (int i = 1; i < n; i++) {
57+
// If the start time of the current activity is greater than or equal to the
58+
// end time of the last selected activity, it means there's no overlap.
3559
if (activities[i][1] >= lastEndTime) {
36-
selectedActivities.add(activities[i][0]);
37-
lastEndTime = activities[i][2];
60+
selectedActivities.add(activities[i][0]); // Select this activity
61+
lastEndTime = activities[i][2]; // Update the end time of the last selected activity
3862
}
3963
}
64+
65+
// Return the list of selected activity indices.
4066
return selectedActivities;
4167
}
4268
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.HashMap;
4+
import java.util.LinkedList;
5+
import java.util.Map;
6+
7+
/**
8+
* Implementation of the Gale-Shapley Algorithm for Stable Matching.
9+
* Problem link: https://en.wikipedia.org/wiki/Stable_marriage_problem
10+
*/
11+
public final class GaleShapley {
12+
13+
private GaleShapley() {
14+
}
15+
16+
/**
17+
* Function to find stable matches between men and women.
18+
*
19+
* @param womenPrefs A map containing women's preferences where each key is a woman and the value is an array of men in order of preference.
20+
* @param menPrefs A map containing men's preferences where each key is a man and the value is an array of women in order of preference.
21+
* @return A map containing stable matches where the key is a woman and the value is her matched man.
22+
*/
23+
public static Map<String, String> stableMatch(Map<String, LinkedList<String>> womenPrefs, Map<String, LinkedList<String>> menPrefs) {
24+
// Initialize all men as free
25+
Map<String, String> engagements = new HashMap<>();
26+
LinkedList<String> freeMen = new LinkedList<>(menPrefs.keySet());
27+
28+
// While there are free men
29+
while (!freeMen.isEmpty()) {
30+
String man = freeMen.poll(); // Get the first free man
31+
LinkedList<String> manPref = menPrefs.get(man); // Get the preferences of the man
32+
33+
// Check if manPref is null or empty
34+
if (manPref == null || manPref.isEmpty()) {
35+
continue; // Skip if no preferences
36+
}
37+
38+
// Propose to the first woman in the man's preference list
39+
String woman = manPref.poll();
40+
String fiance = engagements.get(woman);
41+
42+
// If the woman is not engaged, engage her with the current man
43+
if (fiance == null) {
44+
engagements.put(woman, man);
45+
} else {
46+
// If the woman prefers the current man over her current fiance
47+
LinkedList<String> womanPrefList = womenPrefs.get(woman);
48+
49+
// Check if womanPrefList is null
50+
if (womanPrefList == null) {
51+
continue; // Skip if no preferences for the woman
52+
}
53+
54+
if (womanPrefList.indexOf(man) < womanPrefList.indexOf(fiance)) {
55+
engagements.put(woman, man);
56+
freeMen.add(fiance); // Previous fiance becomes free
57+
} else {
58+
// Woman rejects the new proposal, the man remains free
59+
freeMen.add(man);
60+
}
61+
}
62+
}
63+
return engagements; // Return the stable matches
64+
}
65+
}

src/test/java/com/thealgorithms/backtracking/MColoringTest.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.thealgorithms.backtracking;
22

3-
import static org.junit.jupiter.api.Assertions.assertEquals;
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
45

56
import java.util.ArrayList;
67
import org.junit.jupiter.api.Test;
@@ -16,7 +17,7 @@ void testGraphColoring1() {
1617
int[][] graph = {{0, 1, 1, 1}, {1, 0, 1, 0}, {1, 1, 0, 1}, {1, 0, 1, 0}};
1718
int m = 3; // Number of colors
1819

19-
assertEquals(1, MColoring.possiblePaint(createGraph(graph), n, m));
20+
assertTrue(MColoring.isColoringPossible(createGraph(graph), n, m));
2021
}
2122

2223
@Test
@@ -25,7 +26,7 @@ void testGraphColoring2() {
2526
int[][] graph = {{0, 1, 1, 1, 0}, {1, 0, 0, 1, 0}, {1, 0, 0, 1, 1}, {1, 1, 1, 0, 1}, {0, 0, 1, 1, 0}};
2627
int m = 2; // Number of colors
2728

28-
assertEquals(0, MColoring.possiblePaint(createGraph(graph), n, m));
29+
assertFalse(MColoring.isColoringPossible(createGraph(graph), n, m));
2930
}
3031

3132
@Test
@@ -34,7 +35,7 @@ void testGraphColoring3() {
3435
int[][] graph = {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}};
3536
int m = 2; // Number of colors
3637

37-
assertEquals(0, MColoring.possiblePaint(createGraph(graph), n, m));
38+
assertFalse(MColoring.isColoringPossible(createGraph(graph), n, m));
3839
}
3940

4041
private ArrayList<Node> createGraph(int[][] graph) {
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.HashMap;
6+
import java.util.LinkedList;
7+
import java.util.List;
8+
import java.util.Map;
9+
import org.junit.jupiter.api.Test;
10+
11+
public class GaleShapleyTest {
12+
13+
@Test
14+
public void testStableMatch() {
15+
Map<String, LinkedList<String>> womenPrefs = new HashMap<>();
16+
womenPrefs.put("A", new LinkedList<>(List.of("X", "Y", "Z")));
17+
womenPrefs.put("B", new LinkedList<>(List.of("Y", "X", "Z")));
18+
womenPrefs.put("C", new LinkedList<>(List.of("X", "Y", "Z")));
19+
20+
Map<String, LinkedList<String>> menPrefs = new HashMap<>();
21+
menPrefs.put("X", new LinkedList<>(List.of("A", "B", "C")));
22+
menPrefs.put("Y", new LinkedList<>(List.of("B", "A", "C")));
23+
menPrefs.put("Z", new LinkedList<>(List.of("A", "B", "C")));
24+
25+
Map<String, String> result = GaleShapley.stableMatch(womenPrefs, menPrefs);
26+
27+
Map<String, String> expected = new HashMap<>();
28+
expected.put("A", "X");
29+
expected.put("B", "Y");
30+
expected.put("C", "Z");
31+
32+
assertEquals(expected, result);
33+
}
34+
35+
@Test
36+
public void testSinglePair() {
37+
Map<String, LinkedList<String>> womenPrefs = new HashMap<>();
38+
womenPrefs.put("A", new LinkedList<>(List.of("X")));
39+
40+
Map<String, LinkedList<String>> menPrefs = new HashMap<>();
41+
menPrefs.put("X", new LinkedList<>(List.of("A")));
42+
43+
Map<String, String> result = GaleShapley.stableMatch(womenPrefs, menPrefs);
44+
45+
Map<String, String> expected = new HashMap<>();
46+
expected.put("A", "X");
47+
48+
assertEquals(expected, result);
49+
}
50+
51+
@Test
52+
public void testEqualPreferences() {
53+
Map<String, LinkedList<String>> womenPrefs = new HashMap<>();
54+
womenPrefs.put("A", new LinkedList<>(List.of("X", "Y", "Z")));
55+
womenPrefs.put("B", new LinkedList<>(List.of("X", "Y", "Z")));
56+
womenPrefs.put("C", new LinkedList<>(List.of("X", "Y", "Z")));
57+
58+
Map<String, LinkedList<String>> menPrefs = new HashMap<>();
59+
menPrefs.put("X", new LinkedList<>(List.of("A", "B", "C")));
60+
menPrefs.put("Y", new LinkedList<>(List.of("A", "B", "C")));
61+
menPrefs.put("Z", new LinkedList<>(List.of("A", "B", "C")));
62+
63+
Map<String, String> result = GaleShapley.stableMatch(womenPrefs, menPrefs);
64+
65+
Map<String, String> expected = new HashMap<>();
66+
expected.put("A", "X");
67+
expected.put("B", "Y");
68+
expected.put("C", "Z");
69+
70+
assertEquals(expected, result);
71+
}
72+
}

0 commit comments

Comments
 (0)