Stable marriage problem: Difference between revisions

→‎{{header|J}}: add whitespace, some simplification & rename some nouns and verbs
(→‎{{header|J}}: add whitespace, some simplification & rename some nouns and verbs)
Line 363:
)
 
maleguys=: {."1 mraw
femlgals=: {."1 fraw
 
mprefmprefs=:feml gals i.(}."1 mraw)
fpreffprefs=:male guys i.(}."1 fraw)
 
init=: (,:%)_"0 maleguys NB. initial state: all males unengaged
 
propose=:4 :0dyad define
'engaged etc'=. x
'guy gal'=. y
if. gal e. engaged do.
pref=. gal{fpreffprefs
fiance=. engaged i. gal
if. guy <&(pref&i.) fiance do.
engaged=. gal guy} _ fiance} engaged
end.
else.
engaged=. gal guy} engaged
end.
engaged,:etc
)
 
matchMake=: monad define
GaleShap=:3 :0
'engaged fallback'=. y
whilst. _ e.{.y do.
whilst. _ for_guye. I._={.yengaged do.
for_guy. I. _ ctrl=. <1,guyengaged do.
next=. ctrlguy{yfallback
gal=. (<guy,next){mprefmprefs
yengaged=. yengaged propose guy,gal
yfallback=. (next+1) ctrlguy} yfallback
end.
end.
maleguys,:(engaged{.y){femlgals
)
 
checkStable=: monad define
Stable=:3 :0
guy'ms fs'=.male (guys,:gals) i.{."1 y
gal=.feml i.{:y
satisfied=. ] >: (<0 1) |: ]
mhappymshappy=. satisfied (guyms{mprefmprefs) i."1 0/ galfs
fhappyfshappy=. satisfied (galfs{fpreffprefs) i."1 0/ guyms
stable=. mhappymshappy +. |:fhappyfshappy
if. bad=. 0 e. ,stable do.
smoutput 'Better matches:'
smoutput ((guyms{maleguys),:(galfs{femlgals)) {~"1 0"2 1 ($stable) #: I.,-.stable
end.
assert-.bad
)</lang>
)
</lang>
 
For most of this, males and females are both represented by indices. Rows of mpref<code>mprefs</code> are indexed by a male index and list female indices in priority order. Rows of pref<code>fprefs</code> are indexed by a female index and list male indices in priority order.
 
The key data structure here (the right argument for <code>GaleShapmatchMake</code> and the left argument for <code>propose</code> lists the current engaged partner for each male (an index into femlgals or infinity if not engaged), and the next female on their list to propose to (an index into the columns of mprefmprefs).
 
Example use:
 
<lang> GaleShapmatchMake init
┌───┬────┬───┬───┬───┬────┬───┬───┬────┬───┐
│abe│bob │col│dan│ed │fred│gav│hal│ian │jon│
Line 429 ⟶ 427:
Stability check:
 
<lang j> 1 2 A."_1 GaleShapmatchMake init NB. perturbed matches
┌───┬────┬───┬───┬───┬────┬───┬────┬───┬───┐
│abe│bob │col│dan│ed │fred│gav│hal │jon│ian│
Line 435 ⟶ 433:
│ivy│cath│dee│fay│jan│bea │gay│hope│eve│abi│
└───┴────┴───┴───┴───┴────┴───┴────┴───┴───┘
StablecheckStable 1 2 A."_1 GaleShapmatchMake init
Better matches:
┌───┬────┐
892

edits