Stable marriage problem: Difference between revisions

m
(Added Wren)
m (→‎{{header|Wren}}: Minor tidy)
 
(7 intermediate revisions by 6 users not shown)
Line 52:
# [http://www.ams.org/samplings/feature-column/fc-2015-03 The Stable Marriage Problem and School Choice]. (Excellent exposition)
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V guyprefers = [‘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’]]
V galprefers = [‘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’]]
 
V guys = sorted(guyprefers.keys())
V gals = sorted(galprefers.keys())
 
F check(engaged)
V inverseengaged = Dict(engaged.map((k, v) -> (v, k)))
L(she, he) engaged
V shelikes = :galprefers[she]
V shelikesbetter = shelikes[0 .< shelikes.index(he)]
V helikes = :guyprefers[he]
V helikesbetter = helikes[0 .< helikes.index(she)]
L(guy) shelikesbetter
V guysgirl = inverseengaged[guy]
V guylikes = :guyprefers[guy]
I guylikes.index(guysgirl) > guylikes.index(she)
print(‘#. and #. like each other better than their present partners: #. and #., respectively’.format(she, guy, he, guysgirl))
R 0B
L(gal) helikesbetter
V girlsguy = engaged[gal]
V gallikes = :galprefers[gal]
I gallikes.index(girlsguy) > gallikes.index(he)
print(‘#. and #. like each other better than their present partners: #. and #., respectively’.format(he, gal, she, girlsguy))
R 0B
R 1B
 
F matchmaker()
V guysfree = copy(:guys)
[String = String] engaged
V guyprefers2 = copy(:guyprefers)
V galprefers2 = copy(:galprefers)
L !guysfree.empty
V guy = guysfree.pop(0)
V& guyslist = guyprefers2[guy]
V gal = guyslist.pop(0)
V fiance = engaged.get(gal, ‘’)
I fiance == ‘’
engaged[gal] = guy
print(‘ #. and #.’.format(guy, gal))
E
V galslist = galprefers2[gal]
I galslist.index(fiance) > galslist.index(guy)
engaged[gal] = guy
print(‘ #. dumped #. for #.’.format(gal, fiance, guy))
I !guyprefers2[fiance].empty
guysfree.append(fiance)
E
I !guyslist.empty
guysfree.append(guy)
R engaged
 
print("\nEngagements:")
V engaged = matchmaker()
 
print("\nCouples:")
print(‘ ’sorted(engaged.items()).map((couple_key, couple_val) -> ‘#. is engaged to #.’.format(couple_key, couple_val)).join(",\n "))
print()
print(I check(engaged) {‘Engagement stability check PASSED’} E ‘Engagement stability check FAILED’)
 
print("\n\nSwapping two fiances to introduce an error")
swap(&engaged[gals[0]], &engaged[gals[1]])
L(gal) gals[0.<2]
print(‘ #. is now engaged to #.’.format(gal, engaged[gal]))
print()
print(I check(engaged) {‘Engagement stability check PASSED’} E ‘Engagement stability check FAILED’)</syntaxhighlight>
 
{{out}}
<pre>
 
Engagements:
abe and abi
bob and cath
col and hope
dan and ivy
ed and jan
fred and bea
gav and gay
hope dumped col for ian
abi dumped abe for jon
hal and eve
col and dee
ivy dumped dan for abe
dan and fay
 
Couples:
abi is engaged to jon,
bea is engaged to fred,
cath is engaged to bob,
dee is engaged to col,
eve is engaged to hal,
fay is engaged to dan,
gay is engaged to gav,
hope is engaged to ian,
ivy is engaged to abe,
jan is engaged to ed
 
Engagement stability check PASSED
 
 
Swapping two fiances to introduce an error
abi is now engaged to fred
bea is now engaged to jon
 
fred and bea like each other better than their present partners: abi and jon, respectively
Engagement stability check FAILED
</pre>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey L}}
<langsyntaxhighlight lang="autohotkey">; Given a complete list of ranked preferences, where the most liked is to the left:
abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]
bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]
Line 143 ⟶ 272:
Else
Return "`nThese couples are stable.`n"
}</langsyntaxhighlight>
{{out}}
<pre>Engagements:
Line 199 ⟶ 328:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">:: Stable Marriage Problem in Rosetta Code
:: Batch File Implementation
 
Line 346 ⟶ 475:
set "!%~1.tmp!_=%~2"
set "!%~2.tmp!_=%~1"
goto :EOF</langsyntaxhighlight>
{{Out}}
<pre>HISTORY:
Line 399 ⟶ 528:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
Line 466 ⟶ 595:
NEXT o%
NEXT m%
= TRUE</langsyntaxhighlight>
'''Output:'''
<pre>
Line 488 ⟶ 617:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( (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)
Line 553 ⟶ 682:
| out$stable
)
);</langsyntaxhighlight>
{{out}}
<pre>stable
Line 571 ⟶ 700:
=={{header|C}}==
Oddly enough (or maybe it should be that way, only that I don't know): if the women were proposing instead of the men, the resulting pairs are exactly the same.
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
int verbose = 0;
Line 704 ⟶ 833:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Pairing:
Line 730 ⟶ 859:
=={{header|C sharp|C#}}==
(This is a straight-up translation of the Objective-C version.)
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 854 ⟶ 983:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 873 ⟶ 1,002:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <map>
Line 1,013 ⟶ 1,142:
 
check_stability(engaged, men_pref, women_pref);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,053 ⟶ 1,182:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">abstract class Single(name) of Gal | Guy {
 
shared String name;
Line 1,190 ⟶ 1,319:
}
print("``if(!stabilityFlag) then "Not " else ""``Stable!");
}</langsyntaxhighlight>
{{out}}
<pre>------ the matchmaking process ------
Line 1,231 ⟶ 1,360:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">class Person
constructor: (@name, @preferences) ->
@mate = null
Line 1,358 ⟶ 1,487:
perturb guys
report_on_mates guys
report_potential_adulteries guys</langsyntaxhighlight>
{{out}}
<pre>
Line 1,414 ⟶ 1,543:
 
=={{header|ColdFusion}}==
<langsyntaxhighlight lang="cfm">
PERSON.CFC
 
Line 1,536 ⟶ 1,665:
}
}
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="cfm">
INDEX.CFM
 
Line 1,651 ⟶ 1,780:
}
</cfscript>
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,721 ⟶ 1,850:
=={{header|D}}==
From the Python and Java versions:
<langsyntaxhighlight lang="d">import std.stdio, std.array, std.algorithm, std.string;
 
 
Line 1,850 ⟶ 1,979:
c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
}</langsyntaxhighlight>
{{out}}
<pre>Engagements:
Line 1,876 ⟶ 2,005:
Marriages are unstable</pre>
===Stronger Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array;
 
enum F { abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan }
Line 1,995 ⟶ 2,124:
checkStability(engaged, menPref, womenPref);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Matchmaking:
Line 2,033 ⟶ 2,162:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'hash)
;; input data
Line 2,108 ⟶ 2,237:
(error 'not-stable (list man woman)))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,145 ⟶ 2,274:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let menPrefs =
Map.ofList
["abe", ["abi";"eve";"cath";"ivy";"jan";"dee";"fay";"bea";"hope";"gay"];
Line 2,291 ⟶ 2,420:
husbandOf = solution.husbandOf.Add( gal0, guy1 ).Add( gal1, guy0 ) }
 
printfn "Perturbed is stable: %A" (isStable perturbed)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,309 ⟶ 2,438:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,512 ⟶ 2,641:
fmt.Println("stable.")
return true
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,566 ⟶ 2,695:
 
"Stable Matching" Solution:
<langsyntaxhighlight lang="groovy">import static Man.*
import static Woman.*
 
Line 2,591 ⟶ 2,720:
}
engagedTo
}</langsyntaxhighlight>
 
"Stability Checking" Solution:
(Could do more to eliminate common code. Maybe later.)
<langsyntaxhighlight lang="groovy">boolean isStable(Map<Woman,Man> matches, Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
matches.collect{ girl, guy ->
int guysRank = galsGuyRanking[girl][guy]
Line 2,620 ⟶ 2,749:
true
}.every()
}</langsyntaxhighlight>
 
Test (Stable and Perturbed):
<langsyntaxhighlight lang="groovy">enum Man {
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
}
Line 2,678 ⟶ 2,807:
println ''
 
assert ! isStable(matches, mansWomanRanking, womansManRanking)</langsyntaxhighlight>
{{out}}
<pre>abi (his '10' girl) is engaged to jon (her '8' guy)
Line 2,723 ⟶ 2,852:
The state here consists of the list of free guys and associative preferences lists for guys and girls correspondingly. In order to simplify the access to elements of the state we use lenses.
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE TemplateHaskell #-}
import Lens.Micro
import Lens.Micro.TH
Line 2,734 ⟶ 2,863:
, _girls :: [Preferences a]}
 
makeLenses ''State</langsyntaxhighlight>
 
Lenses allow us to get access to each person in the state, and even to the associated preference list:
 
<langsyntaxhighlight Haskelllang="haskell">name n = lens get set
where get = head . dropWhile ((/= n).fst)
set assoc (_,v) = let (prev, _:post) = break ((== n).fst) assoc
Line 2,744 ⟶ 2,873:
 
fianceesOf n = guys.name n._2
fiancesOf n = girls.name n._2</langsyntaxhighlight>
 
Note that in following we use lens operators:
Line 2,756 ⟶ 2,885:
With these tools and notes we are ready to implement the Gale/Shapley algorithm and the stability test as they are given in a textbook:
 
<langsyntaxhighlight Haskelllang="haskell">stableMatching :: Eq a => State a -> [Couple a]
stableMatching = getPairs . until (null._freeGuys) step
where
Line 2,786 ⟶ 2,915:
, elemIndex w2 fm < elemIndex w1 fm
, let fw = s^.fiancesOf w2
, elemIndex m2 fw < elemIndex m1 fw ]</langsyntaxhighlight>
 
This solution works not only for strings, but for any equable data.
Line 2,794 ⟶ 2,923:
Here are the given preferences:
 
<langsyntaxhighlight Haskelllang="haskell">guys0 =
[("abe", ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]),
("bob", ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]),
Line 2,816 ⟶ 2,945:
("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"])]</langsyntaxhighlight>
The initial state:
 
<langsyntaxhighlight Haskelllang="haskell">s0 = State (fst <$> guys0) guys0 ((_2 %~ reverse) <$> girls0)</langsyntaxhighlight>
 
And the solution:
Line 2,850 ⟶ 2,979:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main()
Line 2,962 ⟶ 3,091:
return X
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 3,014 ⟶ 3,143:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">Mraw=: ;: ;._2 noun define -. ':,'
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
Line 3,085 ⟶ 3,214:
end.
assert-.bad
)</langsyntaxhighlight>
 
For most of this, males and females are both represented by indices. Rows of <code>Mprefs</code> are indexed by a male index and each contains a list female indices, in priority order. Rows of <code>Fprefs</code> are indexed by a female index and each contains a list male indices in priority order. These indices select the corresponding names from <code>GuyNames</code> and <code>GalNames</code>.
Line 3,093 ⟶ 3,222:
Example use:
 
<langsyntaxhighlight lang="j"> matchMake ''
┌───┬────┬───┬───┬───┬────┬───┬───┬────┬───┐
│abe│bob │col│dan│ed │fred│gav│hal│ian │jon│
├───┼────┼───┼───┼───┼────┼───┼───┼────┼───┤
│ivy│cath│dee│fay│jan│bea │gay│eve│hope│abi│
└───┴────┴───┴───┴───┴────┴───┴───┴────┴───┘</langsyntaxhighlight>
 
Stability check:
 
<langsyntaxhighlight lang="j"> checkStable matchMake''
</langsyntaxhighlight>
 
(no news is good news)
Line 3,109 ⟶ 3,238:
An altered result, and a stability check on it (showing what would happen for a bogus result):
 
<langsyntaxhighlight lang="j"> 0 105 A."_1 matchMake '' NB. swap abi and bea
┌───┬────┬───┬───┬───┬────┬───┬───┬────┬───┐
│abe│bob │col│dan│ed │fred│gav│hal│ian │jon│
Line 3,127 ⟶ 3,256:
└────┴───┘
|assertion failure: assert
| assert-.bad</langsyntaxhighlight>
As an aside, note that the guys fared much better than the gals here, with over half of the guys getting their first preference and only one gal getting her first preference. The worst match for any guy was fourth preference where the worst for any gal was seventh preference.
 
=={{header|Java}}==
This is not a direct translation of [[#Python|Python]], but it's fairly close (especially the stability check).
<langsyntaxhighlight lang="java5">import java.util.*;
 
public class Stable {
Line 3,311 ⟶ 3,440:
return true;
}
}</langsyntaxhighlight>
{{out}}
<pre>abi is engaged to jon
Line 3,329 ⟶ 3,458:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function Person(name) {
 
var candidateIndex = 0;
Line 3,450 ⟶ 3,579:
 
doMarriage();
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,466 ⟶ 3,595:
Jon & Fred swap partners
Stable = No</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
 
'''Also works with fq, a Go implementation of a large subset of jq'''
 
This adaptation from [[#Wren]] illustrates
how jq's `debug` facility can be used to
show details about the progress of a computation.
These progress messages could be suppressed,
for example,
by redefining debug/1 as: `def debug(msg): .;`
<syntaxhighlight lang=jq>
# Generic utilities:
def debug(msg): (msg|debug) as $_ | .;
 
# Remove the key named $key from an object specified by the given path
def rmkey($key; path):
path |= with_entries(select(.key != $key));
 
def printPairs:
to_entries[]
| "\(.key) \(.value)";
 
def debugPairs:
. as $in
| reduce to_entries[] as $x (null;
$x | debug("\(.key) \(.value)") )
| $in;
 
# The individual preferences
def mPref : {
"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"]
};
def wPref : {
"abi": {
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": {
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": {
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": {
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": {
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": {
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": {
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": {
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": {
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": {
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10}
};
 
# pair/2 implements the Gale/Shapley algorithm.
# $pPref gives the proposer preferences (like mPref above)
# $rPref gives the recipient preferences (like wPref above)
# Output: a JSON object giving the matching as w:m pairs
def pair($pPref; $rPref):
 
def undo:
debug("engagement: \(.recipient) \(.proposer)")
| .proposals[.recipient] = {proposer, pPref: .ppref, rPref: .rpref}
| rmkey(.proposer; .pFree)
| rmkey(.recipient; .rFree);
 
# preferences must be saved in case engagement is broken;
# they will be saved as: {proposer, pPref, rPref}
{ pFree: $pPref,
rFree: $rPref,
proposals: {} # key is recipient (w)
}
# WP pseudocode comments prefaced with WP: m is proposer, w is recipient.
# WP: while ∃ free man m who still has a woman w to propose to
| until (.pFree|length == 0; # while there is a free proposer ...
# pick a proposer
(.pFree|to_entries[0]) as $me
| .proposer = $me.key
| .ppref = $me.value
| if .ppref|length == 0
then . # if proposer has no possible recipients, skip
# WP: w = m's highest ranked woman to whom he has not yet proposed
else
.recipient = .ppref[0] # highest ranked is first in list
| .ppref = .ppref[1:] # pop from list
# WP: if w is free
| .rpref = .rFree[.recipient]
| if .rpref
then # WP: (m, w) become engaged
undo
else
# WP: else some pair (m', w) already exists
.s = .proposals[.recipient] # get proposal saved preferences
# WP: if w prefers m to m'
| if .s.rPref[.proposer] < .s.rPref[.s.proposer]
then debug("engagement broken: \(.recipient) \(.s.proposer)")
# WP: m' becomes free
| .pFree[.s.proposer] = .s.pPref # return proposer to the map
# WP: (m, w) become engaged
| .rpref = .s.rPref
| undo
else
# WP: else (m', w) remain engaged
.pFree[.proposer] = .ppref # update preferences in map
end
end
end
) # end until
# construct return value
| reduce (.proposals|to_entries)[] as $me ({};
.[$me.key] = $me.value.proposer ) ;
 
# return {result, emit} where .emit is an explanation
def determineStability($ps; $pPref; $rPref):
$ps
| debug("Determining the stability of the following pairings:")
| debugPairs
| to_entries as $pse
| {i:0}
| until(.emit or .i == ($ps|length); # stop after detecting an instability
$pse[.i].key as $r
| $pse[.i].value as $p
| (first($pPref[$p][] as $rp
| if ($r == $rp) then false
else $rPref[$rp] as $rprefs
| if ($rprefs[$p] < $rprefs[$ps[$rp]])
then "\ncauses instability because " +
"\($p) and \($rp) would prefer each other over their current pairings."
else empty
end
end ) // false) as $counterexample
| if $counterexample == false then . else .emit = $counterexample end
| .i += 1 )
| if .emit then {result: false, emit} else {result: true} end ;
 
# Determine pairings using the Gale/Shapley algorithm and then perturb until instability arises.
def task:
pair(mPref; wPref)
| . as $ps
| "Solution:", printPairs,
# verify
((determineStability($ps; mPref; wPref)) as $return
| ($return.emit // empty ),
if $return.result == false
then debug("invalid input")
else
"The result has been validated.",
"Now perturb the result until validation fails.",
(label $done
| foreach range(0; $ps|length -1 ) as $start (.;
.ps = $ps
| (.ps|to_entries) as $kv
| .w2[0] = $kv[$start].key
| .m2[0] = $kv[$start].value
| .w2[1] = $kv[$start+1].key
| .m2[1] = $kv[$start+1].value
| .emit = "\nExchanging partners of \(.m2[0]) and \(.m2[1])"
| .ps[.w2[0]] = .m2[1]
| .ps[.w2[1]] = .m2[0]
# validate perturbed pairings
| determineStability(.ps; mPref; wPref) as $result
| .emit += $result.emit
| .result = $result.result
;
.emit,
if .result == false then break $done else empty end
))
end );
 
task
</syntaxhighlight>
{{output}}
'''Invocation:''' jq -nr -f stable-marriage-problem.jq
<pre>
["DEBUG:","engagement: abi abe"]
["DEBUG:","engagement: cath bob"]
["DEBUG:","engagement: hope col"]
["DEBUG:","engagement: ivy dan"]
["DEBUG:","engagement: jan ed"]
["DEBUG:","engagement: bea fred"]
["DEBUG:","engagement: gay gav"]
["DEBUG:","engagement: eve hal"]
["DEBUG:","engagement broken: hope col"]
["DEBUG:","engagement: hope ian"]
["DEBUG:","engagement broken: abi abe"]
["DEBUG:","engagement: abi jon"]
["DEBUG:","engagement: dee col"]
["DEBUG:","engagement broken: ivy dan"]
["DEBUG:","engagement: ivy abe"]
["DEBUG:","engagement: fay dan"]
Solution:
abi jon
cath bob
hope ian
ivy abe
jan ed
bea fred
gay gav
eve hal
dee col
fay dan
["DEBUG:","Determining the stability of the following pairings:"]
["DEBUG:","abi jon"]
["DEBUG:","cath bob"]
["DEBUG:","hope ian"]
["DEBUG:","ivy abe"]
["DEBUG:","jan ed"]
["DEBUG:","bea fred"]
["DEBUG:","gay gav"]
["DEBUG:","eve hal"]
["DEBUG:","dee col"]
["DEBUG:","fay dan"]
The result has been validated.
Now perturb the result until validation fails.
["DEBUG:","Determining the stability of the following pairings:"]
["DEBUG:","abi bob"]
["DEBUG:","cath jon"]
["DEBUG:","hope ian"]
["DEBUG:","ivy abe"]
["DEBUG:","jan ed"]
["DEBUG:","bea fred"]
["DEBUG:","gay gav"]
["DEBUG:","eve hal"]
["DEBUG:","dee col"]
["DEBUG:","fay dan"]
 
Exchanging partners of jon and bob
causes instability because bob and cath would prefer each other over their current pairings.
</pre>
 
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
# This is not optimized, but tries to follow the pseudocode given the Wikipedia entry below.
# Reference: https://en.wikipedia.org/wiki/Stable_marriage_problem#Algorithm
Line 3,595 ⟶ 3,999:
tableprint("Original Data With Bob and Abe Switched", answer[1], stabl)
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,655 ⟶ 4,059:
=={{header|Kotlin}}==
 
<langsyntaxhighlight lang="java">
data class Person(val name: String) {
val preferences = mutableListOf<Person>()
Line 3,762 ⟶ 4,166:
println("#### match is stable: ${isStableMatch(males, females)}")
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,793 ⟶ 4,197:
{{trans|C#}}
 
<langsyntaxhighlight lang="lua">local Person = {}
Person.__index = Person
 
Line 3,921 ⟶ 4,325:
jon.fiance, fred.fiance = fred.fiance, jon.fiance
print('Stable: ', isStable(men))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,943 ⟶ 4,347:
Stable: false
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica"><<Combinatorica`;
ClearAll[CheckStability]
CheckStabilityHelp[male_, female_, ml_List, fl_List, pairing_List] := Module[{prefs, currentmale},
prefs = fl[[female]];
currentmale = Sort[Reverse /@ pairing][[female, 2]];
FirstPosition[prefs, currentmale][[1]] < FirstPosition[prefs, male][[1]]
]
CheckStabilityHelp[male_, ml_List, fl_List, pairing_List] := Module[{prefs, m, f, p, otherf, reversepair, pos, othermen},
prefs = ml[[male]];
{m, f} = pairing[[male]];
p = FirstPosition[prefs, f][[1]];
otherf = Take[prefs, p - 1];
AllTrue[otherf, CheckStabilityHelp[male, #, ml, fl, pairing] &]
]
CheckStability[ml_List, fl_List, pairing_List] := AllTrue[pairing[[All, 1]], CheckStabilityHelp[#, ml, fl, pairing] &]
males = {"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal",
"ian", "jon"};
females = {"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope",
"ivy", "jan"};
ml = {{"abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea",
"hope", "gay"}, {"cath", "hope", "abi", "dee", "eve", "fay",
"bea", "jan", "ivy", "gay"}, {"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"}, {"ivy", "fay", "dee", "gay",
"hope", "eve", "jan", "bea", "cath", "abi"}, {"jan", "dee", "bea",
"cath", "fay", "eve", "abi", "ivy", "hope", "gay"}, {"bea",
"abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope",
"fay"}, {"gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope",
"jan", "fay"}, {"abi", "eve", "hope", "fay", "ivy", "cath",
"jan", "bea", "gay", "dee"}, {"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"}, {"abi", "fay", "jan", "gay",
"eve", "bea", "dee", "cath", "ivy", "hope"}};
fl = {{"bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col",
"hal"}, {"bob", "abe", "col", "fred", "gav", "dan", "ian", "ed",
"jon", "hal"}, {"fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"}, {"fred", "jon", "col", "abe", "ian", "hal",
"gav", "dan", "bob", "ed"}, {"jon", "hal", "fred", "dan", "abe",
"gav", "col", "ed", "ian", "bob"}, {"bob", "abe", "ed", "ian",
"jon", "dan", "fred", "gav", "col", "hal"}, {"jon", "gav", "hal",
"fred", "bob", "abe", "col", "ed", "dan", "ian"}, {"gav", "jon",
"bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"}, {"ian",
"col", "hal", "gav", "fred", "bob", "abe", "ed", "jon",
"dan"}, {"ed", "hal", "gav", "abe", "bob", "jon", "col", "ian",
"fred", "dan"}};
ml = ml /. Thread[females -> Range[Length[males]]];
fl = fl /. Thread[males -> Range[Length[females]]];
pairing = StableMarriage[ml, fl];
pairing = {Range[Length[pairing]], pairing} // Transpose;
pairing
CheckStability[ml, fl, pairing]
pairing[[{2, 7}, 2]] //= Reverse;
pairing
CheckStability[ml, fl, pairing]</syntaxhighlight>
{{out}}
<pre>{{1,9},{2,3},{3,4},{4,6},{5,10},{6,2},{7,7},{8,5},{9,8},{10,1}}
True
{{1,9},{2,7},{3,4},{4,6},{5,10},{6,2},{7,3},{8,5},{9,8},{10,1}}
False</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sequtils, random, strutils
 
const
Line 4,062 ⟶ 4,525:
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
</syntaxhighlight>
</lang>
{{out}}
<pre>abe 💑 ivy
Line 4,095 ⟶ 4,558:
{{Works with|XCode 4.5.1}}
(The C# version is essentially the same as this.)
<langsyntaxhighlight lang="objc">//--------------------------------------------------------------------
// Person class
 
Line 4,231 ⟶ 4,694:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 4,250 ⟶ 4,713:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let men = [
"abe", ["abi";"eve";"cath";"ivy";"jan";"dee";"fay";"bea";"hope";"gay"];
"bob", ["cath";"hope";"abi";"dee";"eve";"fay";"bea";"jan";"ivy";"gay"];
Line 4,407 ⟶ 4,870:
let engagements = perturb_engagements engagements in
print engagements;
;;</langsyntaxhighlight>
{{out}}
<pre> fay is engaged with dan
Line 4,434 ⟶ 4,897:
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/env perl
use strict;
use warnings;
Line 4,550 ⟶ 5,013:
 
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } }</langsyntaxhighlight>
{{out}}
<pre>
Line 4,581 ⟶ 5,044:
=={{header|Phix}}==
{{trans|AutoHotkey}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant men = {"abe","bob","col","dan","ed","fred","gav","hal","ian","jon"}
<span style="color: #008080;">constant</span> <span style="color: #000000;">men</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"abe"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"bob"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"col"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"dan"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ed"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"fred"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"gav"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"hal"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ian"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"jon"</span><span style="color: #0000FF;">}</span>
enum abe , bob , col , dan , ed , fred , gav , hal , ian , jon
<span style="color: #008080;">enum</span> <span style="color: #000000;">abe</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">bob</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span>
constant hen = {"abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"}
<span style="color: #008080;">constant</span> <span style="color: #000000;">hen</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"abi"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"bea"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"cath"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"dee"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"eve"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"fay"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"gay"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"hope"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ivy"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"jan"</span><span style="color: #0000FF;">}</span>
enum abi , bea , cath , dee , eve , fay , gay , hope , ivy , jan
<span style="color: #008080;">enum</span> <span style="color: #000000;">abi</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span> <span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span>
 
-- Given a complete list of ranked preferences, where the most liked is to the left:
<span style="color: #000080;font-style:italic;">-- Given a complete list of ranked preferences, where the most liked is to the left: </span>
sequence mpref = repeat(0,length(men))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">mpref</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">men</span><span style="color: #0000FF;">))</span>
mpref[abe] = {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">abe</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">}</span>
mpref[bob] = {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">bob</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">}</span>
mpref[col] = {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">}</span>
mpref[dan] = {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dan</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abi</span><span style="color: #0000FF;">}</span>
mpref[ed] = {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ed</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">}</span>
mpref[fred] = {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fred</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">}</span>
mpref[gav] = {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">gav</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">gay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">}</span>
mpref[hal] = {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">hal</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">}</span>
mpref[ian] = {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ian</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">hope</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">}</span>
mpref[jon] = {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope}
<span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">jon</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">abi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gay</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">eve</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bea</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cath</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ivy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hope</span><span style="color: #0000FF;">}</span>
sequence hpref = repeat(0,length(hen))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">hpref</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">))</span>
hpref[abi] = {bob, fred, jon, gav, ian, abe, dan, ed, col, hal}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">abi</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">}</span>
hpref[bea] = {bob, abe, col, fred, gav, dan, ian, ed, jon, hal}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">bea</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">}</span>
hpref[cath] = {fred, bob, ed, gav, hal, col, ian, abe, dan, jon}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cath</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span><span style="color: #0000FF;">}</span>
hpref[dee] = {fred, jon, col, abe, ian, hal, gav, dan, bob, ed}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dee</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">}</span>
hpref[eve] = {jon, hal, fred, dan, abe, gav, col, ed, ian, bob}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">eve</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bob</span><span style="color: #0000FF;">}</span>
hpref[fay] = {bob, abe, ed, ian, jon, dan, fred, gav, col, hal}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fay</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">}</span>
hpref[gay] = {jon, gav, hal, fred, bob, abe, col, ed, dan, ian}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">gay</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">}</span>
hpref[hope] = {gav, jon, bob, abe, ian, dan, hal, ed, col, fred}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">hope</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span><span style="color: #0000FF;">}</span>
hpref[ivy] = {ian, col, hal, gav, fred, bob, abe, ed, jon, dan}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ivy</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">}</span>
hpref[jan] = {ed, hal, gav, abe, bob, jon, col, ian, fred, dan}
<span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">jan</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hal</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gav</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bob</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jon</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ian</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fred</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dan</span><span style="color: #0000FF;">}</span>
 
sequence engagements := repeat(0,length(hen))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">engagements</span> <span style="color: #0000FF;">:=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">))</span>
sequence freemen = tagset(length(men))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">freemen</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">men</span><span style="color: #0000FF;">))</span>
printf(1,"Engagements:\n")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Engagements:\n"</span><span style="color: #0000FF;">)</span>
-- use the Gale Shapley algorithm to find a stable set of engagements:
<span style="color: #000080;font-style:italic;">-- use the Gale Shapley algorithm to find a stable set of engagements:</span>
while length(freemen) do
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">freemen</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer man = freemen[1]
<span style="color: #004080;">integer</span> <span style="color: #000000;">man</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">freemen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
freemen = freemen[2..$]
<span style="color: #000000;">freemen</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">freemen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
integer fem, dumpee
<span style="color: #004080;">integer</span> <span style="color: #000000;">fem</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dumpee</span>
-- each male loops through all females in order of his preference until one accepts him
<span style="color: #000080;font-style:italic;">-- each male loops through all females in order of his preference until one accepts him</span>
for j=1 to length(mpref[man]) do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">man</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">do</span>
fem = mpref[man][j]
<span style="color: #000000;">fem</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">man</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
dumpee = engagements[fem]
<span style="color: #000000;">dumpee</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">engagements</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">]</span>
if dumpee=0
<span style="color: #008080;">if</span> <span style="color: #000000;">dumpee</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
or find(man,hpref[fem])<find(dumpee,hpref[fem]) then
<span style="color: #008080;">or</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">man</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">])<</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dumpee</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">then</span>
exit
<span style="color: #008080;">exit</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if dumpee!=0 then -- if she was previously engaged
<span style="color: #008080;">if</span> <span style="color: #000000;">dumpee</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- if she was previously engaged</span>
freemen &= dumpee -- he goes to the bottom of the list
<span style="color: #000000;">freemen</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">dumpee</span> <span style="color: #000080;font-style:italic;">-- he goes to the bottom of the list</span>
printf(1,"%s dumped %s and accepted %s\n",{hen[fem],men[dumpee],men[man]})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s dumped %s and accepted %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">],</span><span style="color: #000000;">men</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dumpee</span><span style="color: #0000FF;">],</span><span style="color: #000000;">men</span><span style="color: #0000FF;">[</span><span style="color: #000000;">man</span><span style="color: #0000FF;">]})</span>
else
<span style="color: #008080;">else</span>
printf(1,"%s accepted %s\n",{hen[fem],men[man]})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s accepted %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">],</span><span style="color: #000000;">men</span><span style="color: #0000FF;">[</span><span style="color: #000000;">man</span><span style="color: #0000FF;">]})</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
engagements[fem] := man -- the new engagement is registered
<span style="color: #000000;">engagements</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">man</span> <span style="color: #000080;font-style:italic;">-- the new engagement is registered</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
 
printf(1,"\nCouples:\n")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nCouples:\n"</span><span style="color: #0000FF;">)</span>
for fem=1 to length(hen) do
<span style="color: #008080;">for</span> <span style="color: #000000;">fem</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1,"%s is engaged to %s\n",{hen[fem],men[engagements[fem]]})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s is engaged to %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">],</span><span style="color: #000000;">men</span><span style="color: #0000FF;">[</span><span style="color: #000000;">engagements</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">]]})</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
procedure stable()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">stable</span><span style="color: #0000FF;">()</span>
bool unstable = false
<span style="color: #004080;">bool</span> <span style="color: #000000;">unstable</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
for fem=1 to length(hen) do
<span style="color: #008080;">for</span> <span style="color: #000000;">fem</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer man = engagements[fem]
<span style="color: #004080;">integer</span> <span style="color: #000000;">man</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">engagements</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">]</span>
for j=1 to length(hen) do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if find(fem,mpref[man])>find(j,mpref[man])
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">man</span><span style="color: #0000FF;">])></span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">man</span><span style="color: #0000FF;">])</span>
and find(engagements[j],hpref[j])>find(man,hpref[j]) then
<span style="color: #008080;">and</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">engagements</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])></span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">man</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hpref</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">then</span>
if unstable=false then
<span style="color: #008080;">if</span> <span style="color: #000000;">unstable</span><span style="color: #0000FF;">=</span><span style="color: #004600;">false</span> <span style="color: #008080;">then</span>
printf(1,"\nThese couples are not stable.\n")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nThese couples are not stable.\n"</span><span style="color: #0000FF;">)</span>
unstable = true
<span style="color: #000000;">unstable</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,"%s is engaged to %s but would prefer %s and %s is engaged to %s but would prefer %s\n",
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s is engaged to %s but would prefer %s and %s is engaged to %s but would prefer %s\n"</span><span style="color: #0000FF;">,</span>
{men[man],hen[fem],hen[j],hen[j],men[engagements[j]],men[man]})
<span style="color: #0000FF;">{</span><span style="color: #000000;">men</span><span style="color: #0000FF;">[</span><span style="color: #000000;">man</span><span style="color: #0000FF;">],</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fem</span><span style="color: #0000FF;">],</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">hen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">men</span><span style="color: #0000FF;">[</span><span style="color: #000000;">engagements</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]],</span><span style="color: #000000;">men</span><span style="color: #0000FF;">[</span><span style="color: #000000;">man</span><span style="color: #0000FF;">]})</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if not unstable then
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">unstable</span> <span style="color: #008080;">then</span>
printf(1,"\nThese couples are stable.\n")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nThese couples are stable.\n"</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
stable()
<span style="color: #000000;">stable</span><span style="color: #0000FF;">()</span>
printf(1,"\nWhat if cath and ivy swap?\n")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nWhat if cath and ivy swap?\n"</span><span style="color: #0000FF;">)</span>
engagements[cath]:=abe; engagements[ivy]:=bob
<span style="color: #000000;">engagements</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cath</span><span style="color: #0000FF;">]:=</span><span style="color: #000000;">abe</span><span style="color: #0000FF;">;</span> <span style="color: #000000;">engagements</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ivy</span><span style="color: #0000FF;">]:=</span><span style="color: #000000;">bob</span>
stable()</lang>
<span style="color: #000000;">stable</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 4,710 ⟶ 5,175:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq
*Boys (list
(de abe abi eve cath ivy jan dee fay bea hope gay)
Line 4,774 ⟶ 5,239:
(con (asoq 'fred *Couples) 'abi)
(con (asoq 'jon *Couples) 'bea)
(checkCouples)</langsyntaxhighlight>
{{out}}
<pre>dee is engaged to col
Line 4,793 ⟶ 5,258:
gay likes jon better than gav and jon likes gay better than bea
bea likes fred better than jon and fred likes bea better than abi</pre>
 
 
=={{header|PowerShell}}==
<syntaxhighlight lang="PowerShell">
 
using namespace System.Collections.Generic
$ErrorActionPreference = 'Stop'
class Person{
#private
hidden [int] $_candidateIndex;
[string] $Name
#[System.Collections.Generic.List[Person]] $Prefs
[List[Person]] $Prefs
[Person] $Fiance
Person([string] $name) {
$this.Name = $name;
$this.Prefs = $null;
$this.Fiance = $null;
$this._candidateIndex = 0;
}
[bool] Prefers([Person] $p) {
return $this.Prefs.FindIndex({ param($o) $o -eq $p }) -lt $this.Prefs.FindIndex({ param($o) $o -eq $this.Fiance });
}
[Person] NextCandidateNotYetProposedTo() {
if ($this._candidateIndex -ge $this.Prefs.Count) {return $null;}
return $this.Prefs[$this._candidateIndex++];
}
[void] EngageTo([Person] $p) {
if ($p.Fiance -ne $null) {$p.Fiance.Fiance = $null};
$p.Fiance = $this;
if ($this.Fiance -ne $null){$this.Fiance.Fiance = $null};
$this.Fiance = $p;
}
 
}
 
 
class MainClass
{
static [bool] IsStable([List[Person]] $men) {
[List[Person]] $women = $men[0].Prefs;
foreach ($guy in $men){
foreach ($gal in $women) {
if ($guy.Prefers($gal) -and $gal.Prefers($guy))
{return $false};
}
}
return $true;
}
 
static [void] DoMarriage() {
[Person] $abe = [Person]::new("abe");
[Person] $bob = [Person]::new("bob");
[Person] $col = [Person]::new("col");
[Person] $dan = [Person]::new("dan");
[Person] $ed = [Person]::new("ed");
[Person] $fred = [Person]::new("fred");
[Person] $gav = [Person]::new("gav");
[Person] $hal = [Person]::new("hal");
[Person] $ian = [Person]::new("ian");
[Person] $jon = [Person]::new("jon");
[Person] $abi = [Person]::new("abi");
[Person] $bea = [Person]::new("bea");
[Person] $cath = [Person]::new("cath");
[Person] $dee = [Person]::new("dee");
[Person] $eve = [Person]::new("eve");
[Person] $fay = [Person]::new("fay");
[Person] $gay = [Person]::new("gay");
[Person] $hope = [Person]::new("hope");
[Person] $ivy = [Person]::new("ivy");
[Person] $jan = [Person]::new("jan");
 
$abe.Prefs =[Person[]]@($abi, $eve, $cath, $ivy, $jan, $dee, $fay, $bea, $hope, $gay)
$bob.Prefs = [Person[]] @($cath, $hope, $abi, $dee, $eve, $fay, $bea, $jan, $ivy, $gay);
$col.Prefs = [Person[]] @($hope, $eve, $abi, $dee, $bea, $fay, $ivy, $gay, $cath, $jan);
$dan.Prefs = [Person[]] @($ivy, $fay, $dee, $gay, $hope, $eve, $jan, $bea, $cath, $abi);
$ed.Prefs = [Person[]] @($jan, $dee, $bea, $cath, $fay, $eve, $abi, $ivy, $hope, $gay);
$fred.Prefs = [Person[]] @($bea, $abi, $dee, $gay, $eve, $ivy, $cath, $jan, $hope, $fay);
$gav.Prefs = [Person[]] @($gay, $eve, $ivy, $bea, $cath, $abi, $dee, $hope, $jan, $fay);
$hal.Prefs = [Person[]] @($abi, $eve, $hope, $fay, $ivy, $cath, $jan, $bea, $gay, $dee);
$ian.Prefs = [Person[]] @($hope, $cath, $dee, $gay, $bea, $abi, $fay, $ivy, $jan, $eve);
$jon.Prefs = [Person[]] @($abi, $fay, $jan, $gay, $eve, $bea, $dee, $cath, $ivy, $hope);
$abi.Prefs = [Person[]] @($bob, $fred, $jon, $gav, $ian, $abe, $dan, $ed, $col, $hal);
$bea.Prefs = [Person[]] @($bob, $abe, $col, $fred, $gav, $dan, $ian, $ed, $jon, $hal);
$cath.Prefs = [Person[]] @($fred, $bob, $ed, $gav, $hal, $col, $ian, $abe, $dan, $jon);
$dee.Prefs = [Person[]] @($fred, $jon, $col, $abe, $ian, $hal, $gav, $dan, $bob, $ed);
$eve.Prefs = [Person[]] @($jon, $hal, $fred, $dan, $abe, $gav, $col, $ed, $ian, $bob);
$fay.Prefs = [Person[]] @($bob, $abe, $ed, $ian, $jon, $dan, $fred, $gav, $col, $hal);
$gay.Prefs = [Person[]] @($jon, $gav, $hal, $fred, $bob, $abe, $col, $ed, $dan, $ian);
$hope.Prefs = [Person[]] @($gav, $jon, $bob, $abe, $ian, $dan, $hal, $ed, $col, $fred);
$ivy.Prefs = [Person[]] @($ian, $col, $hal, $gav, $fred, $bob, $abe, $ed, $jon, $dan);
$jan.Prefs = [Person[]] @($ed, $hal, $gav, $abe, $bob, $jon, $col, $ian, $fred, $dan);
 
[List[Person]] $men = [List[Person]]::new($abi.Prefs);
 
[int] $freeMenCount = $men.Count;
while ($freeMenCount -gt 0) {
foreach ($guy in $men) {
if ($guy.Fiance -eq $null) {
[Person]$gal = $guy.NextCandidateNotYetProposedTo();
if ($gal.Fiance -eq $null) {
$guy.EngageTo($gal);
$freeMenCount--;
}
else{
if ($gal.Prefers($guy)) {
$guy.EngageTo($gal);
}
}
}
}
}
 
foreach ($guy in $men) {
write-host $guy.Name " is engaged to " $guy.Fiance.Name
}
write-host "Stable = " ([MainClass]::IsStable($men))
write-host "Switching fred & jon's partners";
[Person] $jonsFiance = $jon.Fiance;
[Person] $fredsFiance = $fred.Fiance;
$fred.EngageTo($jonsFiance);
$jon.EngageTo($fredsFiance);
write-host "Stable = " ([MainClass]::IsStable($men));
 
}
static [void] Main([string[]] $args)
{
[MainClass]::DoMarriage();
}
 
 
}
 
[MainClass]::DoMarriage()
 
</syntaxhighlight>
{{out}}
<pre>
bob is engaged to cath
fred is engaged to bea
jon is engaged to abi
gav is engaged to gay
ian is engaged to hope
abe is engaged to ivy
dan is engaged to fay
ed is engaged to jan
col is engaged to dee
hal is engaged to eve
Stable = True
Switching fred & jon's partners
Stable = False
</pre>
 
 
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}{{libheader|XPCE}}
XPCE is used for its integrated messaging system.
<langsyntaxhighlight Prologlang="prolog">%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% facts
prefere(abe,[ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]).
Line 5,070 ⟶ 5,695:
( (IY12 < IY11 , IX21 < IX22);
(IY21 < IY22 , IX12 < IX11)).
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- stable_mariage.
Line 5,097 ⟶ 5,722:
true </pre>
A more Prolog-ish version (working with SWI-Prolog) could be :
<langsyntaxhighlight Prologlang="prolog">:- dynamic person/4, prop/2.
% person(Name, Preference, Status, Candidate)
% prop(Name, List_of_Candidates) (for a woman)
Line 5,310 ⟶ 5,935:
% A couple is unstable
( (IY12 < IY11 , IX21 < IX22);
(IY21 < IY22 , IX12 < IX11)).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
This approach uses a messaging system to pass messages between prospective partners.
<langsyntaxhighlight PureBasiclang="purebasic">#coupleCount = 10
 
DataSection
Line 5,487 ⟶ 6,112:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Marriages:
Line 5,515 ⟶ 6,140:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import copy
 
guyprefers = {
Line 5,617 ⟶ 6,242:
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')</langsyntaxhighlight>
{{out}}
<pre>Engagements:
Line 5,657 ⟶ 6,282:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 5,743 ⟶ 6,368:
(swap! (hash-ref matches (car M)) (hash-ref matches (cadr M))))
(check-stability)
</syntaxhighlight>
</lang>
 
Sample run:
Line 5,767 ⟶ 6,392:
{{Works with|rakudo|2016.10}}
{{trans|Perl}}
<syntaxhighlight lang="raku" perl6line>my %he-likes =
abe => < abi eve cath ivy jan dee fay bea hope gay >,
bob => < cath hope abi dee eve fay bea jan ivy gay >,
Line 5,854 ⟶ 6,479:
engage('fred', 'abi');
engage('jon', 'bea');
}</langsyntaxhighlight>
{{out}}
<pre>Matchmaking:
Line 5,881 ⟶ 6,506:
=={{header|REXX}}==
Algorithm used: see link https://www.youtube.com/watch?v=Qcv1IqHWAzg
<langsyntaxhighlight REXXlang="rexx">/*- REXX --------------------------------------------------------------
* pref.b Preferences of boy b
* pref.g Preferences of girl g
Line 6,085 ⟶ 6,710:
s=left(s,p-1)||new||substr(s,p+length(old))
End
Return s </langsyntaxhighlight>
{{out}}
<pre>
Line 6,111 ⟶ 6,736:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Person
def initialize(name)
@name = name
Line 6,281 ⟶ 6,906:
 
@men.each_value.collect {|man| puts "#{man} + #{man.fiance}"}
stability @men</langsyntaxhighlight>
{{out}}
<pre>abe + ivy
Line 6,317 ⟶ 6,942:
=={{header|Scala}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">object SMP extends App {
private def checkMarriages(): Unit =
if (check)
Line 6,423 ⟶ 7,048:
swap()
checkMarriages()
}</langsyntaxhighlight>
{{out}}
See Java output.
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: preferences is hash [string] array string;
Line 6,577 ⟶ 7,202:
writeln;
writeln("Marriages are " <& [] ("unstable", "stable") [succ(ord(check(engagedTo, guyPrefers, girlPrefers)))]);
end func;</langsyntaxhighlight>
 
Output:
Line 6,619 ⟶ 7,244:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">var he_likes = Hash(
abe => < abi eve cath ivy jan dee fay bea hope gay >,
bob => < cath hope abi dee eve fay bea jan ivy gay >,
Line 6,707 ⟶ 7,332:
 
perturb_em();
check_stability();</langsyntaxhighlight>
{{out}}
<pre>
Line 6,739 ⟶ 7,364:
 
The data set package:
<langsyntaxhighlight lang="ada">package Preferences
is
 
Line 6,782 ⟶ 7,407:
 
end Preferences;
</syntaxhighlight>
</lang>
The package for creating the engagements and checking stability. This package can be analysed by the SPARK tools and proved to be free of any run-time error.
<langsyntaxhighlight lang="ada">with Preferences;
--# inherit Preferences;
package Propose
Line 6,803 ⟶ 7,428:
 
end Propose;
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="ada">with Preferences;
use type Preferences.Extended_Rank;
use type Preferences.Girl;
Line 6,942 ⟶ 7,567:
 
end Propose;
</syntaxhighlight>
</lang>
The test program tests all pairwise exchanges. This is Ada, it is not SPARK.
 
(Text IO is quite tedious in SPARK - it's not what the language was designed for.)
<langsyntaxhighlight lang="ada">------------------------------------
-- Test program.
--
Line 7,012 ⟶ 7,637:
 
end MatchMaker;
</syntaxhighlight>
</lang>
The begining of the output from the test. All pairwise exchanges create unstable pairings.
<pre>ABI marries JON
Line 7,038 ⟶ 7,663:
=={{header|Swift}}==
{{trans|JavaScript}}
<langsyntaxhighlight Swiftlang="swift">class Person {
let name:String
var candidateIndex = 0
Line 7,175 ⟶ 7,800:
}
 
doMarriage()</langsyntaxhighlight>
{{out}}
<pre>
Line 7,194 ⟶ 7,819:
=={{header|Tcl}}==
{{trans|Python}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Functions as aliases to standard commands
Line 7,309 ⟶ 7,934:
}
puts ""
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"</langsyntaxhighlight>
{{out}}
<pre>
Line 7,353 ⟶ 7,978:
{{works with|Bourne Again Shell|4.0}}
{{trans|AutoHotkey}}
<langsyntaxhighlight lang="shell">#!/usr/bin/env bash
main() {
# Our ten males:
Line 7,519 ⟶ 8,144:
}
 
main "$@"</langsyntaxhighlight>
{{Out}}
<pre>abi accepted abe
Line 7,576 ⟶ 8,201:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">men =
 
{
Line 7,623 ⟶ 8,248:
'stable': match/men women,
'perturbed': ~&lSrSxPp match/men women,
'preferred': preferred/(men,women) ~&lSrSxPp match/men women></langsyntaxhighlight>
The matches are perturbed by reversing the order of the women.
{{out}}
Line 7,683 ⟶ 8,308:
 
'''The string approach'''<br/>
<langsyntaxhighlight lang="vb">Sub M_snb()
c00 = "_abe abi eve cath ivy jan dee fay bea hope gay " & _
"_bob cath hope abi dee eve fay bea jan ivy gay " & _
Line 7,726 ⟶ 8,351:
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub</langsyntaxhighlight>
 
'''The Dictionary approach'''
 
<langsyntaxhighlight lang="vb">Sub M_snb()
Set d_00 = CreateObject("scripting.dictionary")
Set d_01 = CreateObject("scripting.dictionary")
Line 7,785 ⟶ 8,410:
MsgBox Join(d_00.items, vbLf)
End Sub</langsyntaxhighlight>
 
{{out}}
Line 7,805 ⟶ 8,430:
{{libheader|Wren-dynamic}}
Although this is a faithful translation, the results are not identical to those of Go as map iteration order in both languages is undefined.
<langsyntaxhighlight ecmascriptlang="wren">import "./dynamic" for Struct
 
var mPref = {
Line 7,975 ⟶ 8,600:
if (!validateStable.call(ps, mPref, wPref)) return
// if those happened to be stable as well, perturb more
}</langsyntaxhighlight>
 
{{out}}
Line 8,032 ⟶ 8,657:
Assume that the input is in XML form as listed [[Stable marriage problem/XSLT input|here]]. The following XSLT 2.0 style-sheet...
 
<syntaxhighlight lang="text"><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
Line 8,167 ⟶ 8,792:
</xsl:function>
</xsl:stylesheet></langsyntaxhighlight>
 
...when applied to the said input document will yield...
 
<syntaxhighlight lang="text"><t>
<m:stable-marriage-problem-result xmlns:m="http://rosettacode.org/wiki/Stable_marriage_problem">
<m:solution is-stable="true">
Line 8,218 ⟶ 8,843:
<m:message>The perturbed configuration is unstable.</m:message>
</m:stable-marriage-problem-result>
</t></langsyntaxhighlight>
 
=={{header|zkl}}==
{{trans|PicoLisp}}
<langsyntaxhighlight lang="zkl">var
Boys=Dictionary(
"abe", "abi eve cath ivy jan dee fay bea hope gay".split(),
Line 8,283 ⟶ 8,908:
Couples.filter1("holds","fred")[1]="abi";
Couples.filter1("holds","jon") [1]="bea";
checkCouples(Couples);</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits