Skip to content

Commit e47b1e2

Browse files
authored
Merge branch 'TheAlgorithms:master' into master
2 parents d1da07d + 842ff52 commit e47b1e2

File tree

6 files changed

+222
-39
lines changed

6 files changed

+222
-39
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
}
Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,55 @@
11
package com.thealgorithms.dynamicprogramming;
22

3-
/* A DynamicProgramming solution for Climbing Stairs' problem Returns the
4-
distinct ways can you climb to the staircase by either climbing 1 or 2 steps.
5-
6-
Link : https://medium.com/analytics-vidhya/leetcode-q70-climbing-stairs-easy-444a4aae54e8
7-
*/
3+
/*
4+
* A dynamic programming solution for the "Climbing Stairs" problem.
5+
* Returns the no. of distinct ways to climb to the top
6+
* of a staircase when you can climb either 1 or 2 steps at a time.
7+
*
8+
* For example, if there are 5 steps, the possible ways to climb the
9+
* staircase are:
10+
* 1. 1-1-1-1-1
11+
* 2. 1-1-1-2
12+
* 3. 1-2-1-1
13+
* 4. 2-1-1-1
14+
* 5. 2-2-1
15+
* 6. 1-1-2-1
16+
* 7. 1-2-2
17+
* 8. 2-1-2
18+
* Ans: 8 ways
19+
*/
820
public final class ClimbingStairs {
21+
922
private ClimbingStairs() {
1023
}
1124

25+
/**
26+
* Calculates the no. of distinct ways to climb a staircase with n steps.
27+
*
28+
* @param n the no. of steps in the staircase (non-negative integer)
29+
* @return the no. of distinct ways to climb to the top
30+
* - Returns 0 if n is 0 (no steps to climb).
31+
* - Returns 1 if n is 1 (only one way to climb).
32+
* - For n > 1, it returns the total no. of ways to climb.
33+
*/
1234
public static int numberOfWays(int n) {
1335

36+
// Base case: if there are no steps or only one step, return n.
1437
if (n == 1 || n == 0) {
1538
return n;
1639
}
17-
int prev = 1;
18-
int curr = 1;
1940

20-
int next;
41+
int prev = 1; // Ways to reach the step before the current one (step 1)
42+
int curr = 1; // Ways to reach the current step (step 2)
43+
int next; // Total ways to reach the next step
2144

22-
for (int i = 2; i <= n; i++) {
45+
for (int i = 2; i <= n; i++) { // step 2 to n
2346
next = curr + prev;
24-
prev = curr;
2547

48+
// Move the pointers to the next step
49+
prev = curr;
2650
curr = next;
2751
}
2852

29-
return curr;
53+
return curr; // Ways to reach the nth step
3054
}
3155
}
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)