-
-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathstable_marriage.jl
70 lines (60 loc) · 2.32 KB
/
stable_marriage.jl
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
using Random
const mnames = ["A", "B", "C", "D"]
const wnames = ["E", "F", "G", "H"]
const Preferences = Dict{String,Vector{String}}
const Pairs = Dict{String,String}
# Returns a name => preference list dictionary, in decreasing order of preference
function genpreferences(mannames::Vector{String}, womannames::Vector{String})
men = Dict(map(m -> (m, shuffle(womannames)), mannames))
women = Dict(map(w -> (w, shuffle(mannames)), womannames))
return men, women
end
# Returns if `person` prefers the `first` candidate over the `second` one.
# This translates to `first` appearing *sooner* in the preference list
prefers(prefs, person, first, second) =
findfirst(m -> m == first, prefs[person]) <
findfirst(m -> m == second, prefs[person])
isfree(person, pairs) = !haskey(pairs, person)
function galeshapley(men::Preferences, women::Preferences)
mentowomen = Dict{String,String}()
womentomen = Dict{String,String}()
while true
bachelors = [m for m in keys(men) if isfree(m, mentowomen)]
if length(bachelors) == 0
return mentowomen, womentomen
end
for bachelor in bachelors
for candidate in men[bachelor]
if isfree(candidate, womentomen)
mentowomen[bachelor] = candidate
womentomen[candidate] = bachelor
break
elseif prefers(women, candidate, bachelor, womentomen[candidate])
delete!(mentowomen, womentomen[candidate])
mentowomen[bachelor] = candidate
womentomen[candidate] = bachelor
break
end
end
end
end
end
function isstable(men::Preferences, women::Preferences, mentowomen::Pairs, womentoman::Pairs)
for (husband, wife) in mentowomen
for candidate in men[husband]
if candidate != wife &&
prefers(men, husband, candidate, wife) &&
prefers(women, candidate, husband, womentoman[candidate])
return false
end
end
end
return true
end
function main()
men, women = genpreferences(mnames, wnames)
mentowomen, womentomen = galeshapley(men, women)
println(mentowomen)
println(isstable(men, women, mentowomen, womentomen) ? "Stable" : "Unstable")
end
main()