Anonymous user
Stable marriage problem: Difference between revisions
Better D alternative version
(Second D version, from the C++ one) |
(Better D alternative version) |
||
Line 540:
Marriages are unstable</pre>
===Alternative version===
<lang d>import std.stdio, std.algorithm, std.array;
enum F { abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan }
enum M { abe, bob, col, dan, ed, fred, gav, hal, ian, jon }
["abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay"],▼
["bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay"],▼
["col", "hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan"],▼
["dan", "ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi"],▼
["ed", "jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay"],▼
["fred", "bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay"],▼
["gav", "gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay"],▼
["hal", "abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee"],▼
["ian", "hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve"],▼
["jon", "abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope"]▼
alias M[][F] PrefMapF;
alias F[][M] PrefMapM;
["abi", "bob","fred","jon","gav","ian","abe","dan","ed","col","hal"],▼
["bea", "bob","abe","col","fred","gav","dan","ian","ed","jon","hal"],▼
["cath", "fred","bob","ed","gav","hal","col","ian","abe","dan","jon"],▼
["dee", "fred","jon","col","abe","ian","hal","gav","dan","bob","ed"],▼
["eve", "jon","hal","fred","dan","abe","gav","col","ed","ian","bob"],▼
["fay", "bob","abe","ed","ian","jon","dan","fred","gav","col","hal"],▼
["gay", "jon","gav","hal","fred","bob","abe","col","ed","dan","ian"],▼
["hope", "gav","jon","bob","abe","ian","dan","hal","ed","col","fred"],▼
["ivy", "ian","col","hal","gav","fred","bob","abe","ed","jon","dan"],▼
["jan", "ed","hal","gav","abe","bob","jon","col","ian","fred","dan"]▼
immutable PrefMapF womenPref;
immutable PrefMapM menPref;
▲alias string[string] Couples;
static this() {
with (F) with (M) {
menPref = [
];
}▼
}
/// Does 'first' appear before 'second' in preference list?
bool prefers(
if (is(T == F) || is(T == M)) {
foreach (p; prefer) {
if (p == first) return true;
Line 582 ⟶ 592:
}
void checkStability(in Couples engaged, in
writeln("Stablility:");
bool stable = true;
Line 605 ⟶ 615:
void main() {
▲ PrefMap menPref, womenPref;
▲ string[] bachelors; // no queue in Phobos
▲ }
▲ }
▲ Couples engaged; // <woman,man>
writeln("Matchmaking:");
Line 650 ⟶ 649:
writeln("Perturb:");
swap(engaged[
writeln("\tengage abi with ", engaged[
checkStability(engaged, menPref, womenPref);
Line 671 ⟶ 670:
Engagements:
abi and jon
hope and ian▼
ivy and abe
eve and hal
cath and bob▼
bea and fred
fay and dan
gay and gav
▲ hope and ian
Stablility:
(all marriages stable)
|