forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GaleShapley.cs
66 lines (58 loc) · 2.13 KB
/
GaleShapley.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Problems.StableMarriage
{
public static class GaleShapley
{
/// <summary>
/// Finds a stable matching between two equal sets of elements (fills EngagedTo properties).
/// time complexity: O(n^2), where n - array size.
/// Guarantees:
/// - Everyone is matched
/// - Matches are stable (there is no better accepter, for any given proposer, which would accept a new match).
/// Presented and proven by David Gale and Lloyd Shapley in 1962.
/// </summary>
public static void Match(Proposer[] proposers, Accepter[] accepters)
{
if (proposers.Length != accepters.Length)
{
throw new ArgumentException("Collections must have equal count");
}
while (proposers.Any(m => !IsEngaged(m)))
{
DoSingleMatchingRound(proposers.Where(m => !IsEngaged(m)));
}
}
private static bool IsEngaged(Proposer proposer) => proposer.EngagedTo is not null;
private static void DoSingleMatchingRound(IEnumerable<Proposer> proposers)
{
foreach (var newProposer in proposers)
{
var accepter = newProposer.PreferenceOrder.First!.Value;
if (accepter.EngagedTo is null)
{
Engage(newProposer, accepter);
}
else
{
if (accepter.PrefersOverCurrent(newProposer))
{
Free(accepter.EngagedTo);
Engage(newProposer, accepter);
}
}
newProposer.PreferenceOrder.RemoveFirst();
}
}
private static void Free(Proposer proposer)
{
proposer.EngagedTo = null;
}
private static void Engage(Proposer proposer, Accepter accepter)
{
proposer.EngagedTo = accepter;
accepter.EngagedTo = proposer;
}
}
}