forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stable-marriage.js
71 lines (59 loc) · 1.53 KB
/
stable-marriage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Person {
constructor(name) {
this.name = name;
}
get hasFiance() {
return !!this.fiance;
}
prefers(other) {
return this.preferences.indexOf(other) < this.preferences.indexOf(this.fiance);
}
engageTo(other) {
if (other.hasFiance) {
other.fiance.fiance = undefined;
}
this.fiance = other;
other.fiance = this;
}
}
function stableMarriage(guys, girls) {
const bachelors = [...guys];
while (bachelors.length > 0) {
const guy = bachelors.shift();
for (const girl of guy.preferences) {
if (!girl.hasFiance) {
guy.engageTo(girl);
break;
} else if (girl.prefers(guy)) {
bachelors.push(girl.fiance);
guy.engageTo(girl);
break;
}
}
}
}
function shuffle(iterable) {
const array = [...iterable];
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const guys = [..."ABCDE"].map(name => new Person(name));
const girls = [..."FGHIJ"].map(name => new Person(name));
console.log("Guys");
for (const guy of guys) {
guy.preferences = shuffle(girls);
console.log(`${guy.name}: ${guy.preferences.map(p => p.name).join()}`)
}
console.log("\nGirls");
for (const girl of girls) {
girl.preferences = shuffle(guys);
console.log(`${girl.name}: ${girl.preferences.map(p => p.name).join()}`)
}
stableMarriage(guys, girls);
console.log("\nPairings");
for (const guy of guys) {
console.log(`${guy.name}: ${guy.fiance.name}`);
}