@@ -20,47 +20,46 @@ private GaleShapley() {
20
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
21
* @return A map containing stable matches where the key is a woman and the value is her matched man.
22
22
*/
23
- public static Map <String , String > stableMatch (Map <String , LinkedList <String >> womenPrefs ,
24
- Map < String , LinkedList < String >> menPrefs ) {
23
+ public static Map <String , String > stableMatch (Map <String , LinkedList <String >> womenPrefs , Map < String , LinkedList < String >> menPrefs ) {
24
+ // Initialize all men as free
25
25
Map <String , String > engagements = new HashMap <>();
26
- Queue <String > freeMen = new LinkedList <>(menPrefs .keySet ());
26
+ LinkedList <String > freeMen = new LinkedList <>(menPrefs .keySet ());
27
27
28
+ // While there are free men
28
29
while (!freeMen .isEmpty ()) {
29
- String man = freeMen .poll ();
30
- LinkedList <String > manPref = menPrefs .get (man );
30
+ String man = freeMen .poll (); // Get the first free man
31
+ LinkedList <String > manPref = menPrefs .get (man ); // Get the preferences of the man
31
32
32
- // Ensure manPref is not null before proceeding
33
- if (manPref == null ) {
34
- continue ;
33
+ // Check if manPref is null or empty
34
+ if (manPref == null || manPref . isEmpty () ) {
35
+ continue ; // Skip if no preferences
35
36
}
36
37
37
38
// Propose to the first woman in the man's preference list
38
39
String woman = manPref .poll ();
39
40
String fiance = engagements .get (woman );
40
41
42
+ // If the woman is not engaged, engage her with the current man
41
43
if (fiance == null ) {
42
- // Woman is free, engage the man and woman
43
44
engagements .put (woman , man );
44
45
} else {
45
- // Woman is already engaged, check if she prefers this man over her current fiance
46
+ // If the woman prefers the current man over her current fiance
46
47
LinkedList <String > womanPrefList = womenPrefs .get (woman );
47
48
48
- // Ensure womanPrefList is not null before comparing
49
+ // Check if womanPrefList is null
49
50
if (womanPrefList == null ) {
50
- continue ;
51
+ continue ; // Skip if no preferences for the woman
51
52
}
52
53
53
- // If the woman prefers the current man over her current fiance
54
54
if (womanPrefList .indexOf (man ) < womanPrefList .indexOf (fiance )) {
55
55
engagements .put (woman , man );
56
56
freeMen .add (fiance ); // Previous fiance becomes free
57
57
} else {
58
- // Woman stays with her current fiance, man remains free
58
+ // Woman rejects the new proposal, the man remains free
59
59
freeMen .add (man );
60
60
}
61
61
}
62
62
}
63
-
64
- return engagements ;
63
+ return engagements ; // Return the stable matches
65
64
}
66
65
}
0 commit comments