#OK to post homework #Natalya Ter-Saakov, Feb 27, Assignment 11 read "C11.txt": read "hw10NatalyaTer-Saakov.txt": #Problem 1: #The Gale-Shapley algorithm: Verbose version GaleSh:=proc(M,W) local n,co,Mrank,Wrank,i,j,CurW,CurH, SinM, SinW,i1: n:=nops(M): if not (type(M,list) and type(W,list) and nops(W)=n) then print(`Bad input`): RETURN(FAIL): fi: for i from 1 to n do if not (type(M[i], list) and nops(M[i])=n and nops(convert(M[i],set))=n and type(W[i], list) and nops(W[i])=n and nops(convert(W[i],set))=n) then print(`Bad input`): RETURN(FAIL): fi: od: co:=0: #Mrank[i]: Ranking of Mr. i of CURRENTLY AVAILABLE WOMEN #Wrank[j]:=Ranking of Ms. j of CURRENTLY AVAILABLE MEN for i from 1 to n do Mrank[i]:=inv(M[i]): od: for j from 1 to n do Wrank[j]:=inv(W[j]): od: #CurW[i]:=Current wife of Mr. i (0 if he is single) #CurH[j]:=Current husband of Ms. j (0 if she is single) for i from 1 to n do CurW[i]:=0: od: for j from 1 to n do CurH[j]:=0: od: SinM:={seq(i,i=1..n)}: SinW:={seq(j,j=1..n)}: while SinM<>{} do #i is the current proposer i:=SinM[1]: #Mr. i proposes to the best remaining woman j:=Mrank[i][1]: #Mr. i1 is the current husband of Ms. j i1:=CurH[j]: co:=co+1: print(`I am Mr.`, i, `Ms. `, j, `would you marry me?`): if i1=0 then print(`Sure, you are my`, W[j][i], `-th choice, but since I am single it does not matter, so sure`): SinM:=SinM minus {i}: SinW:=SinW minus {j}: CurW[i]:=j: CurH[j]:=i: elif W[j][i1]{} do #i is the current proposer i:=SinM[1]: #Mr. i proposes to the best remaining woman j:=Mrank[i][1]: #Mr. i1 is the current husband of Ms. j i1:=CurH[j]: co:=co+1: if i1=0 then SinM:=SinM minus {i}: SinW:=SinW minus {j}: CurW[i]:=j: CurH[j]:=i: elif W[j][i1]M[i][MWprop[i]] then print("Mr.",i,"prefers the wife he would have had if the women proposed"): return(false): fi: if W[i][WMprop[i]]n+1 then return(FAIL) fi: [ops(GaleShT[1], 1..n)], GaleShT[2]: end: #Problem 5 Compare:=proc(n) local K, M,W, fails, stupid, notStupid, st: stupid:=0: notStupid:=0:fails:=0: for K from 1 to 1000 do M,W:=RT(n): st:=FindStable(M,W,10000): if st=FAIL then fails+=1: elif st[2]0 do co+=1: for altPi in FindNeighbors(pi) do t:=CountInstabilities(M,W,altPi): if t