我正在研究java脚本代码(Gale Shapley算法)。我想从数据库或电子表格中读取一些条目,并将代码输出写入另一个数据库或电子表格中。 我的输入是:2个排名偏好矩阵 输出:夫妻(代码中有两个输出,我只需要'夫妻'
代码:
; Given a complete list of ranked preferences, where the most liked is to the left:
bob := ["abi", "dee", "fay", "bea", "jan"]
gav := ["abi", "bea", "dee", "jan", "fay"]
ian := ["bea", "dee", "abi", "fay", "jan"]
jon := ["bea", "abi", "fay", "jan", "dee"]
abi := ["gav", "bob", "jon", "ian"]
bea := ["bob", "gav", "jon", "ian"]
dee := ["jon", "ian", "gav", "bob"]
fay := ["bob", "ian", "jon", "gav"]
jan := ["gav", "bob", "jon", "ian"]
; of ten males:
males := ["bob", "gav", "ian", "jon"]
; and ten females:
females := ["abi", "dee", "fay", "bea", "jan"]
; and an empty set of engagements:
engagements := Object()
freemales := males.Clone()
,s := "Engagements:`n"
; use the Gale Shapley algorithm to find a stable set of engagements:
For i, male in freemales ; i=index of male (not needed)
{
j:=1 ; index of female
While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female]))
j++ ; each male loops through all females in order of his preference until one accepts him
If (engagements[female] != "") ; if she was previously engaged
freemales.insert(engagements[female]) ; her old male goes to the bottom of the list
,s .= female . " dumped " . engagements[female] . "`n"
engagements[female] := male ; the new engagement is registered
,s .= female . " accepted " . male . "`n"
}
; summarize results:
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
Msgbox % clipboard := s
Return
; Functions:
Index(obj, value) {
For key, val in obj
If (val = value)
Return, key, ErrorLevel := 0
Return, False, Errorlevel := 1
}
Stable(engagements, females) {
For female, male in engagements
{
For j, female2 in females ; j=index of female (not needed)
{
If (index(%male%, female) > index(%male%, female2)
and index(%female2%, male2:=engagements[female2]) > index(%female2%, male))
s .= male . " is engaged to " . female . " but would prefer " . female2
. " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n"
}
}
If s
Return "`nThese couples are not stable.`n" . s
Else
Return "`nThese couples are stable.`n"
}