Skip to content

Commit 80cd488

Browse files
authored
Update GaleShapley.java
1 parent 1033808 commit 80cd488

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

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

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,35 +20,47 @@ private GaleShapley() {
2020
* @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.
2121
* @return A map containing stable matches where the key is a woman and the value is her matched man.
2222
*/
23-
public static Map<String, String> stableMatch(Map<String, LinkedList<String>> womenPrefs, Map<String, LinkedList<String>> menPrefs) {
24-
// Initialize all men as free
23+
public static Map<String, String> stableMatch(Map<String, LinkedList<String>> womenPrefs,
24+
Map<String, LinkedList<String>> menPrefs) {
2525
Map<String, String> engagements = new HashMap<>();
26-
LinkedList<String> freeMen = new LinkedList<>(menPrefs.keySet());
26+
Queue<String> freeMen = new LinkedList<>(menPrefs.keySet());
2727

28-
// While there are free men
2928
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
29+
String man = freeMen.poll();
30+
LinkedList<String> manPref = menPrefs.get(man);
31+
32+
// Ensure manPref is not null before proceeding
33+
if (manPref == null) {
34+
continue;
35+
}
3236

3337
// Propose to the first woman in the man's preference list
3438
String woman = manPref.poll();
3539
String fiance = engagements.get(woman);
3640

37-
// If the woman is not engaged, engage her with the current man
3841
if (fiance == null) {
42+
// Woman is free, engage the man and woman
3943
engagements.put(woman, man);
4044
} else {
41-
// If the woman prefers the current man over her current fiance
45+
// Woman is already engaged, check if she prefers this man over her current fiance
4246
LinkedList<String> womanPrefList = womenPrefs.get(woman);
47+
48+
// Ensure womanPrefList is not null before comparing
49+
if (womanPrefList == null) {
50+
continue;
51+
}
52+
53+
// If the woman prefers the current man over her current fiance
4354
if (womanPrefList.indexOf(man) < womanPrefList.indexOf(fiance)) {
4455
engagements.put(woman, man);
4556
freeMen.add(fiance); // Previous fiance becomes free
4657
} else {
47-
// Woman rejects the new proposal, the man remains free
58+
// Woman stays with her current fiance, man remains free
4859
freeMen.add(man);
4960
}
5061
}
5162
}
52-
return engagements; // Return the stable matches
63+
64+
return engagements;
5365
}
5466
}

0 commit comments

Comments
 (0)