Skip to content

Commit 7920387

Browse files
committed
Updating the file to add the GaleShapley algorithm in the greedy algorithms package.
1 parent 80cd488 commit 7920387

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.HashMap;
4+
import java.util.LinkedList;
5+
import java.util.Map;
6+
import java.util.Queue;
7+
8+
public class GaleShapley {
9+
10+
public static Map<String, String> stableMatch(Map<String, LinkedList<String>> womenPrefs, Map<String, LinkedList<String>> menPrefs) {
11+
Map<String, String> engagements = new HashMap<>();
12+
Queue<String> freeMen = new LinkedList<>(menPrefs.keySet());
13+
14+
while (!freeMen.isEmpty()) {
15+
String man = freeMen.poll();
16+
LinkedList<String> manPref = menPrefs.get(man);
17+
18+
if (manPref == null) {
19+
continue;
20+
}
21+
22+
String woman = manPref.poll();
23+
String fiance = engagements.get(woman);
24+
25+
if (fiance == null) {
26+
engagements.put(woman, man);
27+
} else {
28+
LinkedList<String> womanPrefList = womenPrefs.get(woman);
29+
30+
if (womanPrefList == null) {
31+
continue;
32+
}
33+
34+
if (womanPrefList.indexOf(man) < womanPrefList.indexOf(fiance)) {
35+
engagements.put(woman, man);
36+
freeMen.add(fiance);
37+
} else {
38+
freeMen.add(man);
39+
}
40+
}
41+
}
42+
43+
return engagements;
44+
}
45+
}

0 commit comments

Comments
 (0)