Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate a C++ translation of this Groovy snippet without changing its computational steps. | import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys -= thisGuy
List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }
for(Woman girl in guyChoices) {
if(! engagedTo[girl]) {
engagedTo[girl] = thisGuy
break
} else {
Man thatGuy = engagedTo[girl]
if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {
engagedTo[girl] = thisGuy
freeGuys << thatGuy
break
}
}
}
}
engagedTo
}
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Write the same code in Java as shown below in Groovy. | import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys -= thisGuy
List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }
for(Woman girl in guyChoices) {
if(! engagedTo[girl]) {
engagedTo[girl] = thisGuy
break
} else {
Man thatGuy = engagedTo[girl]
if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {
engagedTo[girl] = thisGuy
freeGuys << thatGuy
break
}
}
}
}
engagedTo
}
| import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"});
static Map<String, List<String>> guyPrefers =
new HashMap<String, List<String>>(){{
put("abe",
Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay",
"bea", "hope", "gay"));
put("bob",
Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea",
"jan", "ivy", "gay"));
put("col",
Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy",
"gay", "cath", "jan"));
put("dan",
Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan",
"bea", "cath", "abi"));
put("ed",
Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi",
"ivy", "hope", "gay"));
put("fred",
Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath",
"jan", "hope", "fay"));
put("gav",
Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee",
"hope", "jan", "fay"));
put("hal",
Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan",
"bea", "gay", "dee"));
put("ian",
Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay",
"ivy", "jan", "eve"));
put("jon",
Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee",
"cath", "ivy", "hope"));
}};
static Map<String, List<String>> girlPrefers =
new HashMap<String, List<String>>(){{
put("abi",
Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan",
"ed", "col", "hal"));
put("bea",
Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian",
"ed", "jon", "hal"));
put("cath",
Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"));
put("dee",
Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav",
"dan", "bob", "ed"));
put("eve",
Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col",
"ed", "ian", "bob"));
put("fay",
Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred",
"gav", "col", "hal"));
put("gay",
Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col",
"ed", "dan", "ian"));
put("hope",
Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal",
"ed", "col", "fred"));
put("ivy",
Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe",
"ed", "jon", "dan"));
put("jan",
Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col",
"ian", "fred", "dan"));
}};
public static void main(String[] args){
Map<String, String> matches = match(guys, guyPrefers, girlPrefers);
for(Map.Entry<String, String> couple:matches.entrySet()){
System.out.println(
couple.getKey() + " is engaged to " + couple.getValue());
}
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
String tmp = matches.get(girls.get(0));
matches.put(girls.get(0), matches.get(girls.get(1)));
matches.put(girls.get(1), tmp);
System.out.println(
girls.get(0) +" and " + girls.get(1) + " have switched partners");
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
}
private static Map<String, String> match(List<String> guys,
Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers){
Map<String, String> engagedTo = new TreeMap<String, String>();
List<String> freeGuys = new LinkedList<String>();
freeGuys.addAll(guys);
while(!freeGuys.isEmpty()){
String thisGuy = freeGuys.remove(0);
List<String> thisGuyPrefers = guyPrefers.get(thisGuy);
for(String girl:thisGuyPrefers){
if(engagedTo.get(girl) == null){
engagedTo.put(girl, thisGuy);
break;
}else{
String otherGuy = engagedTo.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(thisGuy) <
thisGirlPrefers.indexOf(otherGuy)){
engagedTo.put(girl, thisGuy);
freeGuys.add(otherGuy);
break;
}
}
}
}
return engagedTo;
}
private static boolean checkMatches(List<String> guys, List<String> girls,
Map<String, String> matches, Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers) {
if(!matches.keySet().containsAll(girls)){
return false;
}
if(!matches.values().containsAll(guys)){
return false;
}
Map<String, String> invertedMatches = new TreeMap<String, String>();
for(Map.Entry<String, String> couple:matches.entrySet()){
invertedMatches.put(couple.getValue(), couple.getKey());
}
for(Map.Entry<String, String> couple:matches.entrySet()){
List<String> shePrefers = girlPrefers.get(couple.getKey());
List<String> sheLikesBetter = new LinkedList<String>();
sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));
List<String> hePrefers = guyPrefers.get(couple.getValue());
List<String> heLikesBetter = new LinkedList<String>();
heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));
for(String guy : sheLikesBetter){
String guysFinace = invertedMatches.get(guy);
List<String> thisGuyPrefers = guyPrefers.get(guy);
if(thisGuyPrefers.indexOf(guysFinace) >
thisGuyPrefers.indexOf(couple.getKey())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getKey(), guy, couple.getValue(),
guy, couple.getKey());
return false;
}
}
for(String girl : heLikesBetter){
String girlsFinace = matches.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(girlsFinace) >
thisGirlPrefers.indexOf(couple.getValue())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getValue(), girl, couple.getKey(),
girl, couple.getValue());
return false;
}
}
}
return true;
}
}
|
Preserve the algorithm and functionality while converting the code from Groovy to Python. | import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys -= thisGuy
List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }
for(Woman girl in guyChoices) {
if(! engagedTo[girl]) {
engagedTo[girl] = thisGuy
break
} else {
Man thatGuy = engagedTo[girl]
if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {
engagedTo[girl] = thisGuy
freeGuys << thatGuy
break
}
}
}
}
engagedTo
}
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Convert this Groovy block to VB, preserving its control flow and logic. | import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys -= thisGuy
List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }
for(Woman girl in guyChoices) {
if(! engagedTo[girl]) {
engagedTo[girl] = thisGuy
break
} else {
Man thatGuy = engagedTo[girl]
if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {
engagedTo[girl] = thisGuy
freeGuys << thatGuy
break
}
}
}
}
engagedTo
}
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Write the same algorithm in Go as shown in this Groovy implementation. | import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys -= thisGuy
List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }
for(Woman girl in guyChoices) {
if(! engagedTo[girl]) {
engagedTo[girl] = thisGuy
break
} else {
Man thatGuy = engagedTo[girl]
if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {
engagedTo[girl] = thisGuy
freeGuys << thatGuy
break
}
}
}
}
engagedTo
}
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Preserve the algorithm and functionality while converting the code from Haskell to C. |
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Haskell. |
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Can you help me rewrite this code in C++ instead of Haskell, keeping it the same logically? |
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Generate a Java translation of this Haskell snippet without changing its computational steps. |
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State
| import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"});
static Map<String, List<String>> guyPrefers =
new HashMap<String, List<String>>(){{
put("abe",
Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay",
"bea", "hope", "gay"));
put("bob",
Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea",
"jan", "ivy", "gay"));
put("col",
Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy",
"gay", "cath", "jan"));
put("dan",
Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan",
"bea", "cath", "abi"));
put("ed",
Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi",
"ivy", "hope", "gay"));
put("fred",
Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath",
"jan", "hope", "fay"));
put("gav",
Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee",
"hope", "jan", "fay"));
put("hal",
Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan",
"bea", "gay", "dee"));
put("ian",
Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay",
"ivy", "jan", "eve"));
put("jon",
Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee",
"cath", "ivy", "hope"));
}};
static Map<String, List<String>> girlPrefers =
new HashMap<String, List<String>>(){{
put("abi",
Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan",
"ed", "col", "hal"));
put("bea",
Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian",
"ed", "jon", "hal"));
put("cath",
Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"));
put("dee",
Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav",
"dan", "bob", "ed"));
put("eve",
Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col",
"ed", "ian", "bob"));
put("fay",
Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred",
"gav", "col", "hal"));
put("gay",
Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col",
"ed", "dan", "ian"));
put("hope",
Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal",
"ed", "col", "fred"));
put("ivy",
Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe",
"ed", "jon", "dan"));
put("jan",
Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col",
"ian", "fred", "dan"));
}};
public static void main(String[] args){
Map<String, String> matches = match(guys, guyPrefers, girlPrefers);
for(Map.Entry<String, String> couple:matches.entrySet()){
System.out.println(
couple.getKey() + " is engaged to " + couple.getValue());
}
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
String tmp = matches.get(girls.get(0));
matches.put(girls.get(0), matches.get(girls.get(1)));
matches.put(girls.get(1), tmp);
System.out.println(
girls.get(0) +" and " + girls.get(1) + " have switched partners");
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
}
private static Map<String, String> match(List<String> guys,
Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers){
Map<String, String> engagedTo = new TreeMap<String, String>();
List<String> freeGuys = new LinkedList<String>();
freeGuys.addAll(guys);
while(!freeGuys.isEmpty()){
String thisGuy = freeGuys.remove(0);
List<String> thisGuyPrefers = guyPrefers.get(thisGuy);
for(String girl:thisGuyPrefers){
if(engagedTo.get(girl) == null){
engagedTo.put(girl, thisGuy);
break;
}else{
String otherGuy = engagedTo.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(thisGuy) <
thisGirlPrefers.indexOf(otherGuy)){
engagedTo.put(girl, thisGuy);
freeGuys.add(otherGuy);
break;
}
}
}
}
return engagedTo;
}
private static boolean checkMatches(List<String> guys, List<String> girls,
Map<String, String> matches, Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers) {
if(!matches.keySet().containsAll(girls)){
return false;
}
if(!matches.values().containsAll(guys)){
return false;
}
Map<String, String> invertedMatches = new TreeMap<String, String>();
for(Map.Entry<String, String> couple:matches.entrySet()){
invertedMatches.put(couple.getValue(), couple.getKey());
}
for(Map.Entry<String, String> couple:matches.entrySet()){
List<String> shePrefers = girlPrefers.get(couple.getKey());
List<String> sheLikesBetter = new LinkedList<String>();
sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));
List<String> hePrefers = guyPrefers.get(couple.getValue());
List<String> heLikesBetter = new LinkedList<String>();
heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));
for(String guy : sheLikesBetter){
String guysFinace = invertedMatches.get(guy);
List<String> thisGuyPrefers = guyPrefers.get(guy);
if(thisGuyPrefers.indexOf(guysFinace) >
thisGuyPrefers.indexOf(couple.getKey())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getKey(), guy, couple.getValue(),
guy, couple.getKey());
return false;
}
}
for(String girl : heLikesBetter){
String girlsFinace = matches.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(girlsFinace) >
thisGirlPrefers.indexOf(couple.getValue())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getValue(), girl, couple.getKey(),
girl, couple.getValue());
return false;
}
}
}
return true;
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Haskell version. |
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Please provide an equivalent version of this Haskell code in VB. |
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Translate this program into Go but keep the logic exactly as in Haskell. |
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Generate an equivalent C version of this Icon code. | link printf
procedure main()
smd := IsStable(ShowEngaged(StableMatching(setup())))
IsStable(ShowEngaged(Swap(\smd,smd.women[1],smd.women[2])))
end
procedure index(L,x)
return ( L[i := 1 to *L] === x, i)
end
procedure ShowEngaged(smd)
printf("\nEngagements:\n")
every w := !smd.women do
printf("%s is engaged to %s\n",w,smd.engaged[w])
return smd
end
procedure Swap(smd,x0,x1)
printf("\nSwapping %s and %s\n",x0,x1)
e := smd.engaged
e[x0] :=: e[x1]
e[e[x0]] := e[e[x1]]
return smd
end
procedure IsStable(smd)
stable := 1
printf("\n")
every mp := smd.prefs[m := !smd.men] &
w := mp[index(mp,smd.engaged[m])-1 to 1 by -1] do {
wp := smd.prefs[w]
if index(wp,smd.engaged[w]) > index(wp,m) then {
printf("Engagement of %s to %s is unstable.\n",w,m)
stable := &null
}
}
if \stable then {
printf("Engagments are all stable.\n")
return smd
}
end
procedure StableMatching(smd)
freemen := copy(smd.men)
freewomen := set(smd.women)
every (prefmen := table())[m := !freemen] := copy(smd.prefs[m])
smd.engaged := engaged := table()
printf("\nMatching:\n")
while m := get(freemen) do {
while w := get(prefmen[m]) do {
if member(freewomen,w) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
printf("%s accepted %s's proposal\n",w,m)
break
}
else {
m0 := engaged[w]
if index(smd.prefs[w],m) < index(smd.prefs[w],m0) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
engaged[m0] := &null
put(freemen,m0)
printf("%s chose %s over %s\n",w,m,m0)
break
}
else next
}
}
}
return smd
end
record sm_data(men,women,prefs,engaged)
procedure setup()
X := sm_data()
X.men := ["abe","bob","col","dan","ed","fred","gav","hal","ian","jon"]
X.women := ["abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"]
if *X.men ~= *(M := set(X.men)) then runerr(500,X.men)
if *X.women ~= *(W := set(X.women)) then runerr(500,X.women)
if *(B := M**W) ~= 0 then runerr(500,B)
X.prefs := p := table()
p["abe"] := ["abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay"]
p["bob"] := ["cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay"]
p["col"] := ["hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan"]
p["dan"] := ["ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi"]
p["ed"] := ["jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay"]
p["fred"] := ["bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay"]
p["gav"] := ["gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay"]
p["hal"] := ["abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee"]
p["ian"] := ["hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve"]
p["jon"] := ["abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope"]
p["abi"] := ["bob","fred","jon","gav","ian","abe","dan","ed","col","hal"]
p["bea"] := ["bob","abe","col","fred","gav","dan","ian","ed","jon","hal"]
p["cath"] := ["fred","bob","ed","gav","hal","col","ian","abe","dan","jon"]
p["dee"] := ["fred","jon","col","abe","ian","hal","gav","dan","bob","ed"]
p["eve"] := ["jon","hal","fred","dan","abe","gav","col","ed","ian","bob"]
p["fay"] := ["bob","abe","ed","ian","jon","dan","fred","gav","col","hal"]
p["gay"] := ["jon","gav","hal","fred","bob","abe","col","ed","dan","ian"]
p["hope"] := ["gav","jon","bob","abe","ian","dan","hal","ed","col","fred"]
p["ivy"] := ["ian","col","hal","gav","fred","bob","abe","ed","jon","dan"]
p["jan"] := ["ed","hal","gav","abe","bob","jon","col","ian","fred","dan"]
return X
end
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Port the following code from Icon to C# with equivalent syntax and logic. | link printf
procedure main()
smd := IsStable(ShowEngaged(StableMatching(setup())))
IsStable(ShowEngaged(Swap(\smd,smd.women[1],smd.women[2])))
end
procedure index(L,x)
return ( L[i := 1 to *L] === x, i)
end
procedure ShowEngaged(smd)
printf("\nEngagements:\n")
every w := !smd.women do
printf("%s is engaged to %s\n",w,smd.engaged[w])
return smd
end
procedure Swap(smd,x0,x1)
printf("\nSwapping %s and %s\n",x0,x1)
e := smd.engaged
e[x0] :=: e[x1]
e[e[x0]] := e[e[x1]]
return smd
end
procedure IsStable(smd)
stable := 1
printf("\n")
every mp := smd.prefs[m := !smd.men] &
w := mp[index(mp,smd.engaged[m])-1 to 1 by -1] do {
wp := smd.prefs[w]
if index(wp,smd.engaged[w]) > index(wp,m) then {
printf("Engagement of %s to %s is unstable.\n",w,m)
stable := &null
}
}
if \stable then {
printf("Engagments are all stable.\n")
return smd
}
end
procedure StableMatching(smd)
freemen := copy(smd.men)
freewomen := set(smd.women)
every (prefmen := table())[m := !freemen] := copy(smd.prefs[m])
smd.engaged := engaged := table()
printf("\nMatching:\n")
while m := get(freemen) do {
while w := get(prefmen[m]) do {
if member(freewomen,w) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
printf("%s accepted %s's proposal\n",w,m)
break
}
else {
m0 := engaged[w]
if index(smd.prefs[w],m) < index(smd.prefs[w],m0) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
engaged[m0] := &null
put(freemen,m0)
printf("%s chose %s over %s\n",w,m,m0)
break
}
else next
}
}
}
return smd
end
record sm_data(men,women,prefs,engaged)
procedure setup()
X := sm_data()
X.men := ["abe","bob","col","dan","ed","fred","gav","hal","ian","jon"]
X.women := ["abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"]
if *X.men ~= *(M := set(X.men)) then runerr(500,X.men)
if *X.women ~= *(W := set(X.women)) then runerr(500,X.women)
if *(B := M**W) ~= 0 then runerr(500,B)
X.prefs := p := table()
p["abe"] := ["abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay"]
p["bob"] := ["cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay"]
p["col"] := ["hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan"]
p["dan"] := ["ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi"]
p["ed"] := ["jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay"]
p["fred"] := ["bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay"]
p["gav"] := ["gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay"]
p["hal"] := ["abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee"]
p["ian"] := ["hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve"]
p["jon"] := ["abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope"]
p["abi"] := ["bob","fred","jon","gav","ian","abe","dan","ed","col","hal"]
p["bea"] := ["bob","abe","col","fred","gav","dan","ian","ed","jon","hal"]
p["cath"] := ["fred","bob","ed","gav","hal","col","ian","abe","dan","jon"]
p["dee"] := ["fred","jon","col","abe","ian","hal","gav","dan","bob","ed"]
p["eve"] := ["jon","hal","fred","dan","abe","gav","col","ed","ian","bob"]
p["fay"] := ["bob","abe","ed","ian","jon","dan","fred","gav","col","hal"]
p["gay"] := ["jon","gav","hal","fred","bob","abe","col","ed","dan","ian"]
p["hope"] := ["gav","jon","bob","abe","ian","dan","hal","ed","col","fred"]
p["ivy"] := ["ian","col","hal","gav","fred","bob","abe","ed","jon","dan"]
p["jan"] := ["ed","hal","gav","abe","bob","jon","col","ian","fred","dan"]
return X
end
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Generate an equivalent C++ version of this Icon code. | link printf
procedure main()
smd := IsStable(ShowEngaged(StableMatching(setup())))
IsStable(ShowEngaged(Swap(\smd,smd.women[1],smd.women[2])))
end
procedure index(L,x)
return ( L[i := 1 to *L] === x, i)
end
procedure ShowEngaged(smd)
printf("\nEngagements:\n")
every w := !smd.women do
printf("%s is engaged to %s\n",w,smd.engaged[w])
return smd
end
procedure Swap(smd,x0,x1)
printf("\nSwapping %s and %s\n",x0,x1)
e := smd.engaged
e[x0] :=: e[x1]
e[e[x0]] := e[e[x1]]
return smd
end
procedure IsStable(smd)
stable := 1
printf("\n")
every mp := smd.prefs[m := !smd.men] &
w := mp[index(mp,smd.engaged[m])-1 to 1 by -1] do {
wp := smd.prefs[w]
if index(wp,smd.engaged[w]) > index(wp,m) then {
printf("Engagement of %s to %s is unstable.\n",w,m)
stable := &null
}
}
if \stable then {
printf("Engagments are all stable.\n")
return smd
}
end
procedure StableMatching(smd)
freemen := copy(smd.men)
freewomen := set(smd.women)
every (prefmen := table())[m := !freemen] := copy(smd.prefs[m])
smd.engaged := engaged := table()
printf("\nMatching:\n")
while m := get(freemen) do {
while w := get(prefmen[m]) do {
if member(freewomen,w) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
printf("%s accepted %s's proposal\n",w,m)
break
}
else {
m0 := engaged[w]
if index(smd.prefs[w],m) < index(smd.prefs[w],m0) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
engaged[m0] := &null
put(freemen,m0)
printf("%s chose %s over %s\n",w,m,m0)
break
}
else next
}
}
}
return smd
end
record sm_data(men,women,prefs,engaged)
procedure setup()
X := sm_data()
X.men := ["abe","bob","col","dan","ed","fred","gav","hal","ian","jon"]
X.women := ["abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"]
if *X.men ~= *(M := set(X.men)) then runerr(500,X.men)
if *X.women ~= *(W := set(X.women)) then runerr(500,X.women)
if *(B := M**W) ~= 0 then runerr(500,B)
X.prefs := p := table()
p["abe"] := ["abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay"]
p["bob"] := ["cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay"]
p["col"] := ["hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan"]
p["dan"] := ["ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi"]
p["ed"] := ["jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay"]
p["fred"] := ["bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay"]
p["gav"] := ["gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay"]
p["hal"] := ["abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee"]
p["ian"] := ["hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve"]
p["jon"] := ["abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope"]
p["abi"] := ["bob","fred","jon","gav","ian","abe","dan","ed","col","hal"]
p["bea"] := ["bob","abe","col","fred","gav","dan","ian","ed","jon","hal"]
p["cath"] := ["fred","bob","ed","gav","hal","col","ian","abe","dan","jon"]
p["dee"] := ["fred","jon","col","abe","ian","hal","gav","dan","bob","ed"]
p["eve"] := ["jon","hal","fred","dan","abe","gav","col","ed","ian","bob"]
p["fay"] := ["bob","abe","ed","ian","jon","dan","fred","gav","col","hal"]
p["gay"] := ["jon","gav","hal","fred","bob","abe","col","ed","dan","ian"]
p["hope"] := ["gav","jon","bob","abe","ian","dan","hal","ed","col","fred"]
p["ivy"] := ["ian","col","hal","gav","fred","bob","abe","ed","jon","dan"]
p["jan"] := ["ed","hal","gav","abe","bob","jon","col","ian","fred","dan"]
return X
end
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Rewrite the snippet below in Python so it works the same as the original Icon code. | link printf
procedure main()
smd := IsStable(ShowEngaged(StableMatching(setup())))
IsStable(ShowEngaged(Swap(\smd,smd.women[1],smd.women[2])))
end
procedure index(L,x)
return ( L[i := 1 to *L] === x, i)
end
procedure ShowEngaged(smd)
printf("\nEngagements:\n")
every w := !smd.women do
printf("%s is engaged to %s\n",w,smd.engaged[w])
return smd
end
procedure Swap(smd,x0,x1)
printf("\nSwapping %s and %s\n",x0,x1)
e := smd.engaged
e[x0] :=: e[x1]
e[e[x0]] := e[e[x1]]
return smd
end
procedure IsStable(smd)
stable := 1
printf("\n")
every mp := smd.prefs[m := !smd.men] &
w := mp[index(mp,smd.engaged[m])-1 to 1 by -1] do {
wp := smd.prefs[w]
if index(wp,smd.engaged[w]) > index(wp,m) then {
printf("Engagement of %s to %s is unstable.\n",w,m)
stable := &null
}
}
if \stable then {
printf("Engagments are all stable.\n")
return smd
}
end
procedure StableMatching(smd)
freemen := copy(smd.men)
freewomen := set(smd.women)
every (prefmen := table())[m := !freemen] := copy(smd.prefs[m])
smd.engaged := engaged := table()
printf("\nMatching:\n")
while m := get(freemen) do {
while w := get(prefmen[m]) do {
if member(freewomen,w) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
printf("%s accepted %s's proposal\n",w,m)
break
}
else {
m0 := engaged[w]
if index(smd.prefs[w],m) < index(smd.prefs[w],m0) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
engaged[m0] := &null
put(freemen,m0)
printf("%s chose %s over %s\n",w,m,m0)
break
}
else next
}
}
}
return smd
end
record sm_data(men,women,prefs,engaged)
procedure setup()
X := sm_data()
X.men := ["abe","bob","col","dan","ed","fred","gav","hal","ian","jon"]
X.women := ["abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"]
if *X.men ~= *(M := set(X.men)) then runerr(500,X.men)
if *X.women ~= *(W := set(X.women)) then runerr(500,X.women)
if *(B := M**W) ~= 0 then runerr(500,B)
X.prefs := p := table()
p["abe"] := ["abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay"]
p["bob"] := ["cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay"]
p["col"] := ["hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan"]
p["dan"] := ["ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi"]
p["ed"] := ["jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay"]
p["fred"] := ["bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay"]
p["gav"] := ["gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay"]
p["hal"] := ["abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee"]
p["ian"] := ["hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve"]
p["jon"] := ["abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope"]
p["abi"] := ["bob","fred","jon","gav","ian","abe","dan","ed","col","hal"]
p["bea"] := ["bob","abe","col","fred","gav","dan","ian","ed","jon","hal"]
p["cath"] := ["fred","bob","ed","gav","hal","col","ian","abe","dan","jon"]
p["dee"] := ["fred","jon","col","abe","ian","hal","gav","dan","bob","ed"]
p["eve"] := ["jon","hal","fred","dan","abe","gav","col","ed","ian","bob"]
p["fay"] := ["bob","abe","ed","ian","jon","dan","fred","gav","col","hal"]
p["gay"] := ["jon","gav","hal","fred","bob","abe","col","ed","dan","ian"]
p["hope"] := ["gav","jon","bob","abe","ian","dan","hal","ed","col","fred"]
p["ivy"] := ["ian","col","hal","gav","fred","bob","abe","ed","jon","dan"]
p["jan"] := ["ed","hal","gav","abe","bob","jon","col","ian","fred","dan"]
return X
end
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Change the programming language of this snippet from Icon to VB without modifying what it does. | link printf
procedure main()
smd := IsStable(ShowEngaged(StableMatching(setup())))
IsStable(ShowEngaged(Swap(\smd,smd.women[1],smd.women[2])))
end
procedure index(L,x)
return ( L[i := 1 to *L] === x, i)
end
procedure ShowEngaged(smd)
printf("\nEngagements:\n")
every w := !smd.women do
printf("%s is engaged to %s\n",w,smd.engaged[w])
return smd
end
procedure Swap(smd,x0,x1)
printf("\nSwapping %s and %s\n",x0,x1)
e := smd.engaged
e[x0] :=: e[x1]
e[e[x0]] := e[e[x1]]
return smd
end
procedure IsStable(smd)
stable := 1
printf("\n")
every mp := smd.prefs[m := !smd.men] &
w := mp[index(mp,smd.engaged[m])-1 to 1 by -1] do {
wp := smd.prefs[w]
if index(wp,smd.engaged[w]) > index(wp,m) then {
printf("Engagement of %s to %s is unstable.\n",w,m)
stable := &null
}
}
if \stable then {
printf("Engagments are all stable.\n")
return smd
}
end
procedure StableMatching(smd)
freemen := copy(smd.men)
freewomen := set(smd.women)
every (prefmen := table())[m := !freemen] := copy(smd.prefs[m])
smd.engaged := engaged := table()
printf("\nMatching:\n")
while m := get(freemen) do {
while w := get(prefmen[m]) do {
if member(freewomen,w) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
printf("%s accepted %s's proposal\n",w,m)
break
}
else {
m0 := engaged[w]
if index(smd.prefs[w],m) < index(smd.prefs[w],m0) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
engaged[m0] := &null
put(freemen,m0)
printf("%s chose %s over %s\n",w,m,m0)
break
}
else next
}
}
}
return smd
end
record sm_data(men,women,prefs,engaged)
procedure setup()
X := sm_data()
X.men := ["abe","bob","col","dan","ed","fred","gav","hal","ian","jon"]
X.women := ["abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"]
if *X.men ~= *(M := set(X.men)) then runerr(500,X.men)
if *X.women ~= *(W := set(X.women)) then runerr(500,X.women)
if *(B := M**W) ~= 0 then runerr(500,B)
X.prefs := p := table()
p["abe"] := ["abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay"]
p["bob"] := ["cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay"]
p["col"] := ["hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan"]
p["dan"] := ["ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi"]
p["ed"] := ["jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay"]
p["fred"] := ["bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay"]
p["gav"] := ["gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay"]
p["hal"] := ["abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee"]
p["ian"] := ["hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve"]
p["jon"] := ["abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope"]
p["abi"] := ["bob","fred","jon","gav","ian","abe","dan","ed","col","hal"]
p["bea"] := ["bob","abe","col","fred","gav","dan","ian","ed","jon","hal"]
p["cath"] := ["fred","bob","ed","gav","hal","col","ian","abe","dan","jon"]
p["dee"] := ["fred","jon","col","abe","ian","hal","gav","dan","bob","ed"]
p["eve"] := ["jon","hal","fred","dan","abe","gav","col","ed","ian","bob"]
p["fay"] := ["bob","abe","ed","ian","jon","dan","fred","gav","col","hal"]
p["gay"] := ["jon","gav","hal","fred","bob","abe","col","ed","dan","ian"]
p["hope"] := ["gav","jon","bob","abe","ian","dan","hal","ed","col","fred"]
p["ivy"] := ["ian","col","hal","gav","fred","bob","abe","ed","jon","dan"]
p["jan"] := ["ed","hal","gav","abe","bob","jon","col","ian","fred","dan"]
return X
end
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Convert the following code from Icon to Go, ensuring the logic remains intact. | link printf
procedure main()
smd := IsStable(ShowEngaged(StableMatching(setup())))
IsStable(ShowEngaged(Swap(\smd,smd.women[1],smd.women[2])))
end
procedure index(L,x)
return ( L[i := 1 to *L] === x, i)
end
procedure ShowEngaged(smd)
printf("\nEngagements:\n")
every w := !smd.women do
printf("%s is engaged to %s\n",w,smd.engaged[w])
return smd
end
procedure Swap(smd,x0,x1)
printf("\nSwapping %s and %s\n",x0,x1)
e := smd.engaged
e[x0] :=: e[x1]
e[e[x0]] := e[e[x1]]
return smd
end
procedure IsStable(smd)
stable := 1
printf("\n")
every mp := smd.prefs[m := !smd.men] &
w := mp[index(mp,smd.engaged[m])-1 to 1 by -1] do {
wp := smd.prefs[w]
if index(wp,smd.engaged[w]) > index(wp,m) then {
printf("Engagement of %s to %s is unstable.\n",w,m)
stable := &null
}
}
if \stable then {
printf("Engagments are all stable.\n")
return smd
}
end
procedure StableMatching(smd)
freemen := copy(smd.men)
freewomen := set(smd.women)
every (prefmen := table())[m := !freemen] := copy(smd.prefs[m])
smd.engaged := engaged := table()
printf("\nMatching:\n")
while m := get(freemen) do {
while w := get(prefmen[m]) do {
if member(freewomen,w) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
printf("%s accepted %s's proposal\n",w,m)
break
}
else {
m0 := engaged[w]
if index(smd.prefs[w],m) < index(smd.prefs[w],m0) then {
engaged[m] := w
engaged[w] := m
delete(freewomen,w)
engaged[m0] := &null
put(freemen,m0)
printf("%s chose %s over %s\n",w,m,m0)
break
}
else next
}
}
}
return smd
end
record sm_data(men,women,prefs,engaged)
procedure setup()
X := sm_data()
X.men := ["abe","bob","col","dan","ed","fred","gav","hal","ian","jon"]
X.women := ["abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"]
if *X.men ~= *(M := set(X.men)) then runerr(500,X.men)
if *X.women ~= *(W := set(X.women)) then runerr(500,X.women)
if *(B := M**W) ~= 0 then runerr(500,B)
X.prefs := p := table()
p["abe"] := ["abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay"]
p["bob"] := ["cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay"]
p["col"] := ["hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan"]
p["dan"] := ["ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi"]
p["ed"] := ["jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay"]
p["fred"] := ["bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay"]
p["gav"] := ["gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay"]
p["hal"] := ["abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee"]
p["ian"] := ["hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve"]
p["jon"] := ["abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope"]
p["abi"] := ["bob","fred","jon","gav","ian","abe","dan","ed","col","hal"]
p["bea"] := ["bob","abe","col","fred","gav","dan","ian","ed","jon","hal"]
p["cath"] := ["fred","bob","ed","gav","hal","col","ian","abe","dan","jon"]
p["dee"] := ["fred","jon","col","abe","ian","hal","gav","dan","bob","ed"]
p["eve"] := ["jon","hal","fred","dan","abe","gav","col","ed","ian","bob"]
p["fay"] := ["bob","abe","ed","ian","jon","dan","fred","gav","col","hal"]
p["gay"] := ["jon","gav","hal","fred","bob","abe","col","ed","dan","ian"]
p["hope"] := ["gav","jon","bob","abe","ian","dan","hal","ed","col","fred"]
p["ivy"] := ["ian","col","hal","gav","fred","bob","abe","ed","jon","dan"]
p["jan"] := ["ed","hal","gav","abe","bob","jon","col","ian","fred","dan"]
return X
end
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Transform the following J implementation into C, maintaining the same output and logic. | 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
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
)
Fraw=: ;: ;._2 noun define -. ':,'
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
)
GuyNames=: {."1 Mraw
GalNames=: {."1 Fraw
Mprefs=: GalNames i. }."1 Mraw
Fprefs=: GuyNames i. }."1 Fraw
propose=: dyad define
engaged=. x
'guy gal'=. y
if. gal e. engaged do.
fiance=. engaged i. gal
if. guy <&((gal{Fprefs)&i.) fiance do.
engaged=. gal guy} _ fiance} engaged
end.
else.
engaged=. gal guy} engaged
end.
engaged
)
matchMake=: monad define
engaged=. _"0 GuyNames
fallback=. 0"0 engaged
whilst. _ e. engaged do.
for_guy. I. _ = engaged do.
next=. guy{fallback
gal=. (<guy,next){Mprefs
engaged=. engaged propose guy,gal
fallback=. (next+1) guy} fallback
end.
end.
GuyNames,:engaged{GalNames
)
checkStable=: monad define
'guys gals'=. (GuyNames,:GalNames) i."1 y
satisfied=. ] >: (<0 1) |: ]
guyshappy=. satisfied (guys{Mprefs) i."1 0/ gals
galshappy=. satisfied (gals{Fprefs) i."1 0/ guys
unstable=. 4$.$.-. guyshappy +. |:galshappy
if. bad=. 0 < #unstable do.
smoutput 'Engagements preferred by both members to their current ones:'
smoutput y {~"1 0"2 1 unstable
end.
assert-.bad
)
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Change the following J code into C# without altering its purpose. | 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
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
)
Fraw=: ;: ;._2 noun define -. ':,'
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
)
GuyNames=: {."1 Mraw
GalNames=: {."1 Fraw
Mprefs=: GalNames i. }."1 Mraw
Fprefs=: GuyNames i. }."1 Fraw
propose=: dyad define
engaged=. x
'guy gal'=. y
if. gal e. engaged do.
fiance=. engaged i. gal
if. guy <&((gal{Fprefs)&i.) fiance do.
engaged=. gal guy} _ fiance} engaged
end.
else.
engaged=. gal guy} engaged
end.
engaged
)
matchMake=: monad define
engaged=. _"0 GuyNames
fallback=. 0"0 engaged
whilst. _ e. engaged do.
for_guy. I. _ = engaged do.
next=. guy{fallback
gal=. (<guy,next){Mprefs
engaged=. engaged propose guy,gal
fallback=. (next+1) guy} fallback
end.
end.
GuyNames,:engaged{GalNames
)
checkStable=: monad define
'guys gals'=. (GuyNames,:GalNames) i."1 y
satisfied=. ] >: (<0 1) |: ]
guyshappy=. satisfied (guys{Mprefs) i."1 0/ gals
galshappy=. satisfied (gals{Fprefs) i."1 0/ guys
unstable=. 4$.$.-. guyshappy +. |:galshappy
if. bad=. 0 < #unstable do.
smoutput 'Engagements preferred by both members to their current ones:'
smoutput y {~"1 0"2 1 unstable
end.
assert-.bad
)
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Preserve the algorithm and functionality while converting the code from J to C++. | 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
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
)
Fraw=: ;: ;._2 noun define -. ':,'
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
)
GuyNames=: {."1 Mraw
GalNames=: {."1 Fraw
Mprefs=: GalNames i. }."1 Mraw
Fprefs=: GuyNames i. }."1 Fraw
propose=: dyad define
engaged=. x
'guy gal'=. y
if. gal e. engaged do.
fiance=. engaged i. gal
if. guy <&((gal{Fprefs)&i.) fiance do.
engaged=. gal guy} _ fiance} engaged
end.
else.
engaged=. gal guy} engaged
end.
engaged
)
matchMake=: monad define
engaged=. _"0 GuyNames
fallback=. 0"0 engaged
whilst. _ e. engaged do.
for_guy. I. _ = engaged do.
next=. guy{fallback
gal=. (<guy,next){Mprefs
engaged=. engaged propose guy,gal
fallback=. (next+1) guy} fallback
end.
end.
GuyNames,:engaged{GalNames
)
checkStable=: monad define
'guys gals'=. (GuyNames,:GalNames) i."1 y
satisfied=. ] >: (<0 1) |: ]
guyshappy=. satisfied (guys{Mprefs) i."1 0/ gals
galshappy=. satisfied (gals{Fprefs) i."1 0/ guys
unstable=. 4$.$.-. guyshappy +. |:galshappy
if. bad=. 0 < #unstable do.
smoutput 'Engagements preferred by both members to their current ones:'
smoutput y {~"1 0"2 1 unstable
end.
assert-.bad
)
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Ensure the translated Java code behaves exactly like the original J snippet. | 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
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
)
Fraw=: ;: ;._2 noun define -. ':,'
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
)
GuyNames=: {."1 Mraw
GalNames=: {."1 Fraw
Mprefs=: GalNames i. }."1 Mraw
Fprefs=: GuyNames i. }."1 Fraw
propose=: dyad define
engaged=. x
'guy gal'=. y
if. gal e. engaged do.
fiance=. engaged i. gal
if. guy <&((gal{Fprefs)&i.) fiance do.
engaged=. gal guy} _ fiance} engaged
end.
else.
engaged=. gal guy} engaged
end.
engaged
)
matchMake=: monad define
engaged=. _"0 GuyNames
fallback=. 0"0 engaged
whilst. _ e. engaged do.
for_guy. I. _ = engaged do.
next=. guy{fallback
gal=. (<guy,next){Mprefs
engaged=. engaged propose guy,gal
fallback=. (next+1) guy} fallback
end.
end.
GuyNames,:engaged{GalNames
)
checkStable=: monad define
'guys gals'=. (GuyNames,:GalNames) i."1 y
satisfied=. ] >: (<0 1) |: ]
guyshappy=. satisfied (guys{Mprefs) i."1 0/ gals
galshappy=. satisfied (gals{Fprefs) i."1 0/ guys
unstable=. 4$.$.-. guyshappy +. |:galshappy
if. bad=. 0 < #unstable do.
smoutput 'Engagements preferred by both members to their current ones:'
smoutput y {~"1 0"2 1 unstable
end.
assert-.bad
)
| import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"});
static Map<String, List<String>> guyPrefers =
new HashMap<String, List<String>>(){{
put("abe",
Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay",
"bea", "hope", "gay"));
put("bob",
Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea",
"jan", "ivy", "gay"));
put("col",
Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy",
"gay", "cath", "jan"));
put("dan",
Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan",
"bea", "cath", "abi"));
put("ed",
Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi",
"ivy", "hope", "gay"));
put("fred",
Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath",
"jan", "hope", "fay"));
put("gav",
Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee",
"hope", "jan", "fay"));
put("hal",
Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan",
"bea", "gay", "dee"));
put("ian",
Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay",
"ivy", "jan", "eve"));
put("jon",
Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee",
"cath", "ivy", "hope"));
}};
static Map<String, List<String>> girlPrefers =
new HashMap<String, List<String>>(){{
put("abi",
Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan",
"ed", "col", "hal"));
put("bea",
Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian",
"ed", "jon", "hal"));
put("cath",
Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"));
put("dee",
Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav",
"dan", "bob", "ed"));
put("eve",
Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col",
"ed", "ian", "bob"));
put("fay",
Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred",
"gav", "col", "hal"));
put("gay",
Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col",
"ed", "dan", "ian"));
put("hope",
Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal",
"ed", "col", "fred"));
put("ivy",
Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe",
"ed", "jon", "dan"));
put("jan",
Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col",
"ian", "fred", "dan"));
}};
public static void main(String[] args){
Map<String, String> matches = match(guys, guyPrefers, girlPrefers);
for(Map.Entry<String, String> couple:matches.entrySet()){
System.out.println(
couple.getKey() + " is engaged to " + couple.getValue());
}
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
String tmp = matches.get(girls.get(0));
matches.put(girls.get(0), matches.get(girls.get(1)));
matches.put(girls.get(1), tmp);
System.out.println(
girls.get(0) +" and " + girls.get(1) + " have switched partners");
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
}
private static Map<String, String> match(List<String> guys,
Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers){
Map<String, String> engagedTo = new TreeMap<String, String>();
List<String> freeGuys = new LinkedList<String>();
freeGuys.addAll(guys);
while(!freeGuys.isEmpty()){
String thisGuy = freeGuys.remove(0);
List<String> thisGuyPrefers = guyPrefers.get(thisGuy);
for(String girl:thisGuyPrefers){
if(engagedTo.get(girl) == null){
engagedTo.put(girl, thisGuy);
break;
}else{
String otherGuy = engagedTo.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(thisGuy) <
thisGirlPrefers.indexOf(otherGuy)){
engagedTo.put(girl, thisGuy);
freeGuys.add(otherGuy);
break;
}
}
}
}
return engagedTo;
}
private static boolean checkMatches(List<String> guys, List<String> girls,
Map<String, String> matches, Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers) {
if(!matches.keySet().containsAll(girls)){
return false;
}
if(!matches.values().containsAll(guys)){
return false;
}
Map<String, String> invertedMatches = new TreeMap<String, String>();
for(Map.Entry<String, String> couple:matches.entrySet()){
invertedMatches.put(couple.getValue(), couple.getKey());
}
for(Map.Entry<String, String> couple:matches.entrySet()){
List<String> shePrefers = girlPrefers.get(couple.getKey());
List<String> sheLikesBetter = new LinkedList<String>();
sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));
List<String> hePrefers = guyPrefers.get(couple.getValue());
List<String> heLikesBetter = new LinkedList<String>();
heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));
for(String guy : sheLikesBetter){
String guysFinace = invertedMatches.get(guy);
List<String> thisGuyPrefers = guyPrefers.get(guy);
if(thisGuyPrefers.indexOf(guysFinace) >
thisGuyPrefers.indexOf(couple.getKey())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getKey(), guy, couple.getValue(),
guy, couple.getKey());
return false;
}
}
for(String girl : heLikesBetter){
String girlsFinace = matches.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(girlsFinace) >
thisGirlPrefers.indexOf(couple.getValue())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getValue(), girl, couple.getKey(),
girl, couple.getValue());
return false;
}
}
}
return true;
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the J version. | 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
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
)
Fraw=: ;: ;._2 noun define -. ':,'
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
)
GuyNames=: {."1 Mraw
GalNames=: {."1 Fraw
Mprefs=: GalNames i. }."1 Mraw
Fprefs=: GuyNames i. }."1 Fraw
propose=: dyad define
engaged=. x
'guy gal'=. y
if. gal e. engaged do.
fiance=. engaged i. gal
if. guy <&((gal{Fprefs)&i.) fiance do.
engaged=. gal guy} _ fiance} engaged
end.
else.
engaged=. gal guy} engaged
end.
engaged
)
matchMake=: monad define
engaged=. _"0 GuyNames
fallback=. 0"0 engaged
whilst. _ e. engaged do.
for_guy. I. _ = engaged do.
next=. guy{fallback
gal=. (<guy,next){Mprefs
engaged=. engaged propose guy,gal
fallback=. (next+1) guy} fallback
end.
end.
GuyNames,:engaged{GalNames
)
checkStable=: monad define
'guys gals'=. (GuyNames,:GalNames) i."1 y
satisfied=. ] >: (<0 1) |: ]
guyshappy=. satisfied (guys{Mprefs) i."1 0/ gals
galshappy=. satisfied (gals{Fprefs) i."1 0/ guys
unstable=. 4$.$.-. guyshappy +. |:galshappy
if. bad=. 0 < #unstable do.
smoutput 'Engagements preferred by both members to their current ones:'
smoutput y {~"1 0"2 1 unstable
end.
assert-.bad
)
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Write the same algorithm in VB as shown in this J implementation. | 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
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
)
Fraw=: ;: ;._2 noun define -. ':,'
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
)
GuyNames=: {."1 Mraw
GalNames=: {."1 Fraw
Mprefs=: GalNames i. }."1 Mraw
Fprefs=: GuyNames i. }."1 Fraw
propose=: dyad define
engaged=. x
'guy gal'=. y
if. gal e. engaged do.
fiance=. engaged i. gal
if. guy <&((gal{Fprefs)&i.) fiance do.
engaged=. gal guy} _ fiance} engaged
end.
else.
engaged=. gal guy} engaged
end.
engaged
)
matchMake=: monad define
engaged=. _"0 GuyNames
fallback=. 0"0 engaged
whilst. _ e. engaged do.
for_guy. I. _ = engaged do.
next=. guy{fallback
gal=. (<guy,next){Mprefs
engaged=. engaged propose guy,gal
fallback=. (next+1) guy} fallback
end.
end.
GuyNames,:engaged{GalNames
)
checkStable=: monad define
'guys gals'=. (GuyNames,:GalNames) i."1 y
satisfied=. ] >: (<0 1) |: ]
guyshappy=. satisfied (guys{Mprefs) i."1 0/ gals
galshappy=. satisfied (gals{Fprefs) i."1 0/ guys
unstable=. 4$.$.-. guyshappy +. |:galshappy
if. bad=. 0 < #unstable do.
smoutput 'Engagements preferred by both members to their current ones:'
smoutput y {~"1 0"2 1 unstable
end.
assert-.bad
)
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Transform the following J implementation into Go, maintaining the same output and logic. | 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
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
)
Fraw=: ;: ;._2 noun define -. ':,'
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
)
GuyNames=: {."1 Mraw
GalNames=: {."1 Fraw
Mprefs=: GalNames i. }."1 Mraw
Fprefs=: GuyNames i. }."1 Fraw
propose=: dyad define
engaged=. x
'guy gal'=. y
if. gal e. engaged do.
fiance=. engaged i. gal
if. guy <&((gal{Fprefs)&i.) fiance do.
engaged=. gal guy} _ fiance} engaged
end.
else.
engaged=. gal guy} engaged
end.
engaged
)
matchMake=: monad define
engaged=. _"0 GuyNames
fallback=. 0"0 engaged
whilst. _ e. engaged do.
for_guy. I. _ = engaged do.
next=. guy{fallback
gal=. (<guy,next){Mprefs
engaged=. engaged propose guy,gal
fallback=. (next+1) guy} fallback
end.
end.
GuyNames,:engaged{GalNames
)
checkStable=: monad define
'guys gals'=. (GuyNames,:GalNames) i."1 y
satisfied=. ] >: (<0 1) |: ]
guyshappy=. satisfied (guys{Mprefs) i."1 0/ gals
galshappy=. satisfied (gals{Fprefs) i."1 0/ guys
unstable=. 4$.$.-. guyshappy +. |:galshappy
if. bad=. 0 < #unstable do.
smoutput 'Engagements preferred by both members to their current ones:'
smoutput y {~"1 0"2 1 unstable
end.
assert-.bad
)
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Translate this program into C but keep the logic exactly as in Julia. |
const males = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
const females = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
const malepreferences = Dict(
"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"]
)
const femalepreferences = Dict(
"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"]
)
function pshuf(d)
ret = Dict()
for (k,v) in d
ret[k] = shuffle(v)
end
ret
end
pindexin(a, p) = ([i for i in 1:length(a) if a[i] == p])[1]
prefers(d, p1, p2, p3) = (pindexin(d[p1], p2) < pindexin(d[p1], p3))
function isstable(mmatchup, fmatchup, mpref, fpref)
for (mmatch, fmatch) in mmatchup
for f in mpref[mmatch]
if(f != fmatch && prefers(mpref, mmatch, f, fmatch)
&& prefers(fpref, f, mmatch, fmatchup[f]))
println("$mmatch prefers $f and $f prefers $mmatch over their current partners.")
return false
end
end
end
true
end
function galeshapley(men, women, malepref, femalepref)
mfree = Dict([(p, true) for p in men])
wfree = Dict([(p, true) for p in women])
mpairs = Dict()
wpairs = Dict()
while true
bachelors = [p for p in keys(mfree) if mfree[p]]
if(length(bachelors) == 0)
return mpairs, wpairs
end
for m in bachelors
for w in malepref[m]
if(wfree[w])
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
wfree[w] = false
break
elseif(prefers(femalepref, w, m, wpairs[w]))
mfree[wpairs[w]] = true
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
break
end
end
end
end
end
function tableprint(txt, ans, stab)
println(txt)
println(" Man Woman")
println(" ----- -----")
show(STDOUT, "text/plain", ans)
if(stab)
println("\n ----STABLE----\n\n")
else
println("\n ---UNSTABLE---\n\n")
end
end
println("Use the Gale Shapley algorithm to find a stable set of engagements.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data Table", answer[1], stabl)
println("To check this is not a one-off solution, run the function on a randomized sample.")
newmpref = pshuf(malepreferences)
newfpref = pshuf(femalepreferences)
answer = galeshapley(males, females, newmpref, newfpref)
stabl = isstable(answer[1], answer[2], newmpref, newfpref)
tableprint("Shuffled Preferences", answer[1], stabl)
println("Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
fia1 = (answer[1])["abe"]
fia2 = (answer[1])["bob"]
answer[1]["abe"] = fia2
answer[1]["bob"] = fia1
answer[2][fia1] = "bob"
answer[2][fia2] = "abe"
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data With Bob and Abe Switched", answer[1], stabl)
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Change the following Julia code into C# without altering its purpose. |
const males = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
const females = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
const malepreferences = Dict(
"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"]
)
const femalepreferences = Dict(
"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"]
)
function pshuf(d)
ret = Dict()
for (k,v) in d
ret[k] = shuffle(v)
end
ret
end
pindexin(a, p) = ([i for i in 1:length(a) if a[i] == p])[1]
prefers(d, p1, p2, p3) = (pindexin(d[p1], p2) < pindexin(d[p1], p3))
function isstable(mmatchup, fmatchup, mpref, fpref)
for (mmatch, fmatch) in mmatchup
for f in mpref[mmatch]
if(f != fmatch && prefers(mpref, mmatch, f, fmatch)
&& prefers(fpref, f, mmatch, fmatchup[f]))
println("$mmatch prefers $f and $f prefers $mmatch over their current partners.")
return false
end
end
end
true
end
function galeshapley(men, women, malepref, femalepref)
mfree = Dict([(p, true) for p in men])
wfree = Dict([(p, true) for p in women])
mpairs = Dict()
wpairs = Dict()
while true
bachelors = [p for p in keys(mfree) if mfree[p]]
if(length(bachelors) == 0)
return mpairs, wpairs
end
for m in bachelors
for w in malepref[m]
if(wfree[w])
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
wfree[w] = false
break
elseif(prefers(femalepref, w, m, wpairs[w]))
mfree[wpairs[w]] = true
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
break
end
end
end
end
end
function tableprint(txt, ans, stab)
println(txt)
println(" Man Woman")
println(" ----- -----")
show(STDOUT, "text/plain", ans)
if(stab)
println("\n ----STABLE----\n\n")
else
println("\n ---UNSTABLE---\n\n")
end
end
println("Use the Gale Shapley algorithm to find a stable set of engagements.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data Table", answer[1], stabl)
println("To check this is not a one-off solution, run the function on a randomized sample.")
newmpref = pshuf(malepreferences)
newfpref = pshuf(femalepreferences)
answer = galeshapley(males, females, newmpref, newfpref)
stabl = isstable(answer[1], answer[2], newmpref, newfpref)
tableprint("Shuffled Preferences", answer[1], stabl)
println("Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
fia1 = (answer[1])["abe"]
fia2 = (answer[1])["bob"]
answer[1]["abe"] = fia2
answer[1]["bob"] = fia1
answer[2][fia1] = "bob"
answer[2][fia2] = "abe"
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data With Bob and Abe Switched", answer[1], stabl)
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Write a version of this Julia function in C++ with identical behavior. |
const males = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
const females = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
const malepreferences = Dict(
"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"]
)
const femalepreferences = Dict(
"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"]
)
function pshuf(d)
ret = Dict()
for (k,v) in d
ret[k] = shuffle(v)
end
ret
end
pindexin(a, p) = ([i for i in 1:length(a) if a[i] == p])[1]
prefers(d, p1, p2, p3) = (pindexin(d[p1], p2) < pindexin(d[p1], p3))
function isstable(mmatchup, fmatchup, mpref, fpref)
for (mmatch, fmatch) in mmatchup
for f in mpref[mmatch]
if(f != fmatch && prefers(mpref, mmatch, f, fmatch)
&& prefers(fpref, f, mmatch, fmatchup[f]))
println("$mmatch prefers $f and $f prefers $mmatch over their current partners.")
return false
end
end
end
true
end
function galeshapley(men, women, malepref, femalepref)
mfree = Dict([(p, true) for p in men])
wfree = Dict([(p, true) for p in women])
mpairs = Dict()
wpairs = Dict()
while true
bachelors = [p for p in keys(mfree) if mfree[p]]
if(length(bachelors) == 0)
return mpairs, wpairs
end
for m in bachelors
for w in malepref[m]
if(wfree[w])
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
wfree[w] = false
break
elseif(prefers(femalepref, w, m, wpairs[w]))
mfree[wpairs[w]] = true
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
break
end
end
end
end
end
function tableprint(txt, ans, stab)
println(txt)
println(" Man Woman")
println(" ----- -----")
show(STDOUT, "text/plain", ans)
if(stab)
println("\n ----STABLE----\n\n")
else
println("\n ---UNSTABLE---\n\n")
end
end
println("Use the Gale Shapley algorithm to find a stable set of engagements.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data Table", answer[1], stabl)
println("To check this is not a one-off solution, run the function on a randomized sample.")
newmpref = pshuf(malepreferences)
newfpref = pshuf(femalepreferences)
answer = galeshapley(males, females, newmpref, newfpref)
stabl = isstable(answer[1], answer[2], newmpref, newfpref)
tableprint("Shuffled Preferences", answer[1], stabl)
println("Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
fia1 = (answer[1])["abe"]
fia2 = (answer[1])["bob"]
answer[1]["abe"] = fia2
answer[1]["bob"] = fia1
answer[2][fia1] = "bob"
answer[2][fia2] = "abe"
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data With Bob and Abe Switched", answer[1], stabl)
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Translate the given Julia code snippet into Python without altering its behavior. |
const males = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
const females = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
const malepreferences = Dict(
"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"]
)
const femalepreferences = Dict(
"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"]
)
function pshuf(d)
ret = Dict()
for (k,v) in d
ret[k] = shuffle(v)
end
ret
end
pindexin(a, p) = ([i for i in 1:length(a) if a[i] == p])[1]
prefers(d, p1, p2, p3) = (pindexin(d[p1], p2) < pindexin(d[p1], p3))
function isstable(mmatchup, fmatchup, mpref, fpref)
for (mmatch, fmatch) in mmatchup
for f in mpref[mmatch]
if(f != fmatch && prefers(mpref, mmatch, f, fmatch)
&& prefers(fpref, f, mmatch, fmatchup[f]))
println("$mmatch prefers $f and $f prefers $mmatch over their current partners.")
return false
end
end
end
true
end
function galeshapley(men, women, malepref, femalepref)
mfree = Dict([(p, true) for p in men])
wfree = Dict([(p, true) for p in women])
mpairs = Dict()
wpairs = Dict()
while true
bachelors = [p for p in keys(mfree) if mfree[p]]
if(length(bachelors) == 0)
return mpairs, wpairs
end
for m in bachelors
for w in malepref[m]
if(wfree[w])
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
wfree[w] = false
break
elseif(prefers(femalepref, w, m, wpairs[w]))
mfree[wpairs[w]] = true
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
break
end
end
end
end
end
function tableprint(txt, ans, stab)
println(txt)
println(" Man Woman")
println(" ----- -----")
show(STDOUT, "text/plain", ans)
if(stab)
println("\n ----STABLE----\n\n")
else
println("\n ---UNSTABLE---\n\n")
end
end
println("Use the Gale Shapley algorithm to find a stable set of engagements.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data Table", answer[1], stabl)
println("To check this is not a one-off solution, run the function on a randomized sample.")
newmpref = pshuf(malepreferences)
newfpref = pshuf(femalepreferences)
answer = galeshapley(males, females, newmpref, newfpref)
stabl = isstable(answer[1], answer[2], newmpref, newfpref)
tableprint("Shuffled Preferences", answer[1], stabl)
println("Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
fia1 = (answer[1])["abe"]
fia2 = (answer[1])["bob"]
answer[1]["abe"] = fia2
answer[1]["bob"] = fia1
answer[2][fia1] = "bob"
answer[2][fia2] = "abe"
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data With Bob and Abe Switched", answer[1], stabl)
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Produce a functionally identical VB code for the snippet given in Julia. |
const males = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
const females = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
const malepreferences = Dict(
"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"]
)
const femalepreferences = Dict(
"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"]
)
function pshuf(d)
ret = Dict()
for (k,v) in d
ret[k] = shuffle(v)
end
ret
end
pindexin(a, p) = ([i for i in 1:length(a) if a[i] == p])[1]
prefers(d, p1, p2, p3) = (pindexin(d[p1], p2) < pindexin(d[p1], p3))
function isstable(mmatchup, fmatchup, mpref, fpref)
for (mmatch, fmatch) in mmatchup
for f in mpref[mmatch]
if(f != fmatch && prefers(mpref, mmatch, f, fmatch)
&& prefers(fpref, f, mmatch, fmatchup[f]))
println("$mmatch prefers $f and $f prefers $mmatch over their current partners.")
return false
end
end
end
true
end
function galeshapley(men, women, malepref, femalepref)
mfree = Dict([(p, true) for p in men])
wfree = Dict([(p, true) for p in women])
mpairs = Dict()
wpairs = Dict()
while true
bachelors = [p for p in keys(mfree) if mfree[p]]
if(length(bachelors) == 0)
return mpairs, wpairs
end
for m in bachelors
for w in malepref[m]
if(wfree[w])
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
wfree[w] = false
break
elseif(prefers(femalepref, w, m, wpairs[w]))
mfree[wpairs[w]] = true
mpairs[m] = w
wpairs[w] = m
mfree[m] = false
break
end
end
end
end
end
function tableprint(txt, ans, stab)
println(txt)
println(" Man Woman")
println(" ----- -----")
show(STDOUT, "text/plain", ans)
if(stab)
println("\n ----STABLE----\n\n")
else
println("\n ---UNSTABLE---\n\n")
end
end
println("Use the Gale Shapley algorithm to find a stable set of engagements.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data Table", answer[1], stabl)
println("To check this is not a one-off solution, run the function on a randomized sample.")
newmpref = pshuf(malepreferences)
newfpref = pshuf(femalepreferences)
answer = galeshapley(males, females, newmpref, newfpref)
stabl = isstable(answer[1], answer[2], newmpref, newfpref)
tableprint("Shuffled Preferences", answer[1], stabl)
println("Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
fia1 = (answer[1])["abe"]
fia2 = (answer[1])["bob"]
answer[1]["abe"] = fia2
answer[1]["bob"] = fia1
answer[2][fia1] = "bob"
answer[2][fia2] = "abe"
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data With Bob and Abe Switched", answer[1], stabl)
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Port the following code from Lua to C# with equivalent syntax and logic. | local Person = {}
Person.__index = Person
function Person.new(inName)
local o = {
name = inName,
prefs = nil,
fiance = nil,
_candidateIndex = 1,
}
return setmetatable(o, Person)
end
function Person:indexOf(other)
for i, p in pairs(self.prefs) do
if p == other then return i end
end
return 999
end
function Person:prefers(other)
return self:indexOf(other) < self:indexOf(self.fiance)
end
function Person:nextCandidateNotYetProposedTo()
if self._candidateIndex >= #self.prefs then return nil end
local c = self.prefs[self._candidateIndex];
self._candidateIndex = self._candidateIndex + 1
return c;
end
function Person:engageTo(other)
if other.fiance then
other.fiance.fiance = nil
end
other.fiance = self
if self.fiance then
self.fiance.fiance = nil
end
self.fiance = other;
end
local function isStable(men)
local women = men[1].prefs
local stable = true
for _, guy in pairs(men) do
for _, gal in pairs(women) do
if guy:prefers(gal) and gal:prefers(guy) then
stable = false
print(guy.name .. ' and ' .. gal.name ..
' prefer each other over their partners ' ..
guy.fiance.name .. ' and ' .. gal.fiance.name)
end
end
end
return stable
end
local abe = Person.new("Abe")
local bob = Person.new("Bob")
local col = Person.new("Col")
local dan = Person.new("Dan")
local ed = Person.new("Ed")
local fred = Person.new("Fred")
local gav = Person.new("Gav")
local hal = Person.new("Hal")
local ian = Person.new("Ian")
local jon = Person.new("Jon")
local abi = Person.new("Abi")
local bea = Person.new("Bea")
local cath = Person.new("Cath")
local dee = Person.new("Dee")
local eve = Person.new("Eve")
local fay = Person.new("Fay")
local gay = Person.new("Gay")
local hope = Person.new("Hope")
local ivy = Person.new("Ivy")
local jan = Person.new("Jan")
abe.prefs = { abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay }
bob.prefs = { cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay }
col.prefs = { hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan }
dan.prefs = { ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi }
ed.prefs = { jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay }
fred.prefs = { bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay }
gav.prefs = { gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay }
hal.prefs = { abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee }
ian.prefs = { hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve }
jon.prefs = { abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope }
abi.prefs = { bob, fred, jon, gav, ian, abe, dan, ed, col, hal }
bea.prefs = { bob, abe, col, fred, gav, dan, ian, ed, jon, hal }
cath.prefs = { fred, bob, ed, gav, hal, col, ian, abe, dan, jon }
dee.prefs = { fred, jon, col, abe, ian, hal, gav, dan, bob, ed }
eve.prefs = { jon, hal, fred, dan, abe, gav, col, ed, ian, bob }
fay.prefs = { bob, abe, ed, ian, jon, dan, fred, gav, col, hal }
gay.prefs = { jon, gav, hal, fred, bob, abe, col, ed, dan, ian }
hope.prefs = { gav, jon, bob, abe, ian, dan, hal, ed, col, fred }
ivy.prefs = { ian, col, hal, gav, fred, bob, abe, ed, jon, dan }
jan.prefs = { ed, hal, gav, abe, bob, jon, col, ian, fred, dan }
local men = abi.prefs
local freeMenCount = #men
while freeMenCount > 0 do
for _, guy in pairs(men) do
if not guy.fiance then
local gal = guy:nextCandidateNotYetProposedTo()
if not gal.fiance then
guy:engageTo(gal)
freeMenCount = freeMenCount - 1
elseif gal:prefers(guy) then
guy:engageTo(gal)
end
end
end
end
print(' ')
for _, guy in pairs(men) do
print(guy.name .. ' is engaged to ' .. guy.fiance.name)
end
print('Stable: ', isStable(men))
print(' ')
print('Switching ' .. fred.name .. "'s & " .. jon.name .. "'s partners")
jon.fiance, fred.fiance = fred.fiance, jon.fiance
print('Stable: ', isStable(men))
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Produce a functionally identical C++ code for the snippet given in Lua. | local Person = {}
Person.__index = Person
function Person.new(inName)
local o = {
name = inName,
prefs = nil,
fiance = nil,
_candidateIndex = 1,
}
return setmetatable(o, Person)
end
function Person:indexOf(other)
for i, p in pairs(self.prefs) do
if p == other then return i end
end
return 999
end
function Person:prefers(other)
return self:indexOf(other) < self:indexOf(self.fiance)
end
function Person:nextCandidateNotYetProposedTo()
if self._candidateIndex >= #self.prefs then return nil end
local c = self.prefs[self._candidateIndex];
self._candidateIndex = self._candidateIndex + 1
return c;
end
function Person:engageTo(other)
if other.fiance then
other.fiance.fiance = nil
end
other.fiance = self
if self.fiance then
self.fiance.fiance = nil
end
self.fiance = other;
end
local function isStable(men)
local women = men[1].prefs
local stable = true
for _, guy in pairs(men) do
for _, gal in pairs(women) do
if guy:prefers(gal) and gal:prefers(guy) then
stable = false
print(guy.name .. ' and ' .. gal.name ..
' prefer each other over their partners ' ..
guy.fiance.name .. ' and ' .. gal.fiance.name)
end
end
end
return stable
end
local abe = Person.new("Abe")
local bob = Person.new("Bob")
local col = Person.new("Col")
local dan = Person.new("Dan")
local ed = Person.new("Ed")
local fred = Person.new("Fred")
local gav = Person.new("Gav")
local hal = Person.new("Hal")
local ian = Person.new("Ian")
local jon = Person.new("Jon")
local abi = Person.new("Abi")
local bea = Person.new("Bea")
local cath = Person.new("Cath")
local dee = Person.new("Dee")
local eve = Person.new("Eve")
local fay = Person.new("Fay")
local gay = Person.new("Gay")
local hope = Person.new("Hope")
local ivy = Person.new("Ivy")
local jan = Person.new("Jan")
abe.prefs = { abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay }
bob.prefs = { cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay }
col.prefs = { hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan }
dan.prefs = { ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi }
ed.prefs = { jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay }
fred.prefs = { bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay }
gav.prefs = { gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay }
hal.prefs = { abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee }
ian.prefs = { hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve }
jon.prefs = { abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope }
abi.prefs = { bob, fred, jon, gav, ian, abe, dan, ed, col, hal }
bea.prefs = { bob, abe, col, fred, gav, dan, ian, ed, jon, hal }
cath.prefs = { fred, bob, ed, gav, hal, col, ian, abe, dan, jon }
dee.prefs = { fred, jon, col, abe, ian, hal, gav, dan, bob, ed }
eve.prefs = { jon, hal, fred, dan, abe, gav, col, ed, ian, bob }
fay.prefs = { bob, abe, ed, ian, jon, dan, fred, gav, col, hal }
gay.prefs = { jon, gav, hal, fred, bob, abe, col, ed, dan, ian }
hope.prefs = { gav, jon, bob, abe, ian, dan, hal, ed, col, fred }
ivy.prefs = { ian, col, hal, gav, fred, bob, abe, ed, jon, dan }
jan.prefs = { ed, hal, gav, abe, bob, jon, col, ian, fred, dan }
local men = abi.prefs
local freeMenCount = #men
while freeMenCount > 0 do
for _, guy in pairs(men) do
if not guy.fiance then
local gal = guy:nextCandidateNotYetProposedTo()
if not gal.fiance then
guy:engageTo(gal)
freeMenCount = freeMenCount - 1
elseif gal:prefers(guy) then
guy:engageTo(gal)
end
end
end
end
print(' ')
for _, guy in pairs(men) do
print(guy.name .. ' is engaged to ' .. guy.fiance.name)
end
print('Stable: ', isStable(men))
print(' ')
print('Switching ' .. fred.name .. "'s & " .. jon.name .. "'s partners")
jon.fiance, fred.fiance = fred.fiance, jon.fiance
print('Stable: ', isStable(men))
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Rewrite the snippet below in Python so it works the same as the original Lua code. | local Person = {}
Person.__index = Person
function Person.new(inName)
local o = {
name = inName,
prefs = nil,
fiance = nil,
_candidateIndex = 1,
}
return setmetatable(o, Person)
end
function Person:indexOf(other)
for i, p in pairs(self.prefs) do
if p == other then return i end
end
return 999
end
function Person:prefers(other)
return self:indexOf(other) < self:indexOf(self.fiance)
end
function Person:nextCandidateNotYetProposedTo()
if self._candidateIndex >= #self.prefs then return nil end
local c = self.prefs[self._candidateIndex];
self._candidateIndex = self._candidateIndex + 1
return c;
end
function Person:engageTo(other)
if other.fiance then
other.fiance.fiance = nil
end
other.fiance = self
if self.fiance then
self.fiance.fiance = nil
end
self.fiance = other;
end
local function isStable(men)
local women = men[1].prefs
local stable = true
for _, guy in pairs(men) do
for _, gal in pairs(women) do
if guy:prefers(gal) and gal:prefers(guy) then
stable = false
print(guy.name .. ' and ' .. gal.name ..
' prefer each other over their partners ' ..
guy.fiance.name .. ' and ' .. gal.fiance.name)
end
end
end
return stable
end
local abe = Person.new("Abe")
local bob = Person.new("Bob")
local col = Person.new("Col")
local dan = Person.new("Dan")
local ed = Person.new("Ed")
local fred = Person.new("Fred")
local gav = Person.new("Gav")
local hal = Person.new("Hal")
local ian = Person.new("Ian")
local jon = Person.new("Jon")
local abi = Person.new("Abi")
local bea = Person.new("Bea")
local cath = Person.new("Cath")
local dee = Person.new("Dee")
local eve = Person.new("Eve")
local fay = Person.new("Fay")
local gay = Person.new("Gay")
local hope = Person.new("Hope")
local ivy = Person.new("Ivy")
local jan = Person.new("Jan")
abe.prefs = { abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay }
bob.prefs = { cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay }
col.prefs = { hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan }
dan.prefs = { ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi }
ed.prefs = { jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay }
fred.prefs = { bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay }
gav.prefs = { gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay }
hal.prefs = { abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee }
ian.prefs = { hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve }
jon.prefs = { abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope }
abi.prefs = { bob, fred, jon, gav, ian, abe, dan, ed, col, hal }
bea.prefs = { bob, abe, col, fred, gav, dan, ian, ed, jon, hal }
cath.prefs = { fred, bob, ed, gav, hal, col, ian, abe, dan, jon }
dee.prefs = { fred, jon, col, abe, ian, hal, gav, dan, bob, ed }
eve.prefs = { jon, hal, fred, dan, abe, gav, col, ed, ian, bob }
fay.prefs = { bob, abe, ed, ian, jon, dan, fred, gav, col, hal }
gay.prefs = { jon, gav, hal, fred, bob, abe, col, ed, dan, ian }
hope.prefs = { gav, jon, bob, abe, ian, dan, hal, ed, col, fred }
ivy.prefs = { ian, col, hal, gav, fred, bob, abe, ed, jon, dan }
jan.prefs = { ed, hal, gav, abe, bob, jon, col, ian, fred, dan }
local men = abi.prefs
local freeMenCount = #men
while freeMenCount > 0 do
for _, guy in pairs(men) do
if not guy.fiance then
local gal = guy:nextCandidateNotYetProposedTo()
if not gal.fiance then
guy:engageTo(gal)
freeMenCount = freeMenCount - 1
elseif gal:prefers(guy) then
guy:engageTo(gal)
end
end
end
end
print(' ')
for _, guy in pairs(men) do
print(guy.name .. ' is engaged to ' .. guy.fiance.name)
end
print('Stable: ', isStable(men))
print(' ')
print('Switching ' .. fred.name .. "'s & " .. jon.name .. "'s partners")
jon.fiance, fred.fiance = fred.fiance, jon.fiance
print('Stable: ', isStable(men))
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Translate this program into VB but keep the logic exactly as in Lua. | local Person = {}
Person.__index = Person
function Person.new(inName)
local o = {
name = inName,
prefs = nil,
fiance = nil,
_candidateIndex = 1,
}
return setmetatable(o, Person)
end
function Person:indexOf(other)
for i, p in pairs(self.prefs) do
if p == other then return i end
end
return 999
end
function Person:prefers(other)
return self:indexOf(other) < self:indexOf(self.fiance)
end
function Person:nextCandidateNotYetProposedTo()
if self._candidateIndex >= #self.prefs then return nil end
local c = self.prefs[self._candidateIndex];
self._candidateIndex = self._candidateIndex + 1
return c;
end
function Person:engageTo(other)
if other.fiance then
other.fiance.fiance = nil
end
other.fiance = self
if self.fiance then
self.fiance.fiance = nil
end
self.fiance = other;
end
local function isStable(men)
local women = men[1].prefs
local stable = true
for _, guy in pairs(men) do
for _, gal in pairs(women) do
if guy:prefers(gal) and gal:prefers(guy) then
stable = false
print(guy.name .. ' and ' .. gal.name ..
' prefer each other over their partners ' ..
guy.fiance.name .. ' and ' .. gal.fiance.name)
end
end
end
return stable
end
local abe = Person.new("Abe")
local bob = Person.new("Bob")
local col = Person.new("Col")
local dan = Person.new("Dan")
local ed = Person.new("Ed")
local fred = Person.new("Fred")
local gav = Person.new("Gav")
local hal = Person.new("Hal")
local ian = Person.new("Ian")
local jon = Person.new("Jon")
local abi = Person.new("Abi")
local bea = Person.new("Bea")
local cath = Person.new("Cath")
local dee = Person.new("Dee")
local eve = Person.new("Eve")
local fay = Person.new("Fay")
local gay = Person.new("Gay")
local hope = Person.new("Hope")
local ivy = Person.new("Ivy")
local jan = Person.new("Jan")
abe.prefs = { abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay }
bob.prefs = { cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay }
col.prefs = { hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan }
dan.prefs = { ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi }
ed.prefs = { jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay }
fred.prefs = { bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay }
gav.prefs = { gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay }
hal.prefs = { abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee }
ian.prefs = { hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve }
jon.prefs = { abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope }
abi.prefs = { bob, fred, jon, gav, ian, abe, dan, ed, col, hal }
bea.prefs = { bob, abe, col, fred, gav, dan, ian, ed, jon, hal }
cath.prefs = { fred, bob, ed, gav, hal, col, ian, abe, dan, jon }
dee.prefs = { fred, jon, col, abe, ian, hal, gav, dan, bob, ed }
eve.prefs = { jon, hal, fred, dan, abe, gav, col, ed, ian, bob }
fay.prefs = { bob, abe, ed, ian, jon, dan, fred, gav, col, hal }
gay.prefs = { jon, gav, hal, fred, bob, abe, col, ed, dan, ian }
hope.prefs = { gav, jon, bob, abe, ian, dan, hal, ed, col, fred }
ivy.prefs = { ian, col, hal, gav, fred, bob, abe, ed, jon, dan }
jan.prefs = { ed, hal, gav, abe, bob, jon, col, ian, fred, dan }
local men = abi.prefs
local freeMenCount = #men
while freeMenCount > 0 do
for _, guy in pairs(men) do
if not guy.fiance then
local gal = guy:nextCandidateNotYetProposedTo()
if not gal.fiance then
guy:engageTo(gal)
freeMenCount = freeMenCount - 1
elseif gal:prefers(guy) then
guy:engageTo(gal)
end
end
end
end
print(' ')
for _, guy in pairs(men) do
print(guy.name .. ' is engaged to ' .. guy.fiance.name)
end
print('Stable: ', isStable(men))
print(' ')
print('Switching ' .. fred.name .. "'s & " .. jon.name .. "'s partners")
jon.fiance, fred.fiance = fred.fiance, jon.fiance
print('Stable: ', isStable(men))
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Generate a C translation of this Mathematica snippet without changing its computational steps. | <<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]
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Rewrite the snippet below in C# so it works the same as the original Mathematica code. | <<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]
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Port the following code from Mathematica to C++ with equivalent syntax and logic. | <<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]
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Generate an equivalent Java version of this Mathematica code. | <<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]
| import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"});
static Map<String, List<String>> guyPrefers =
new HashMap<String, List<String>>(){{
put("abe",
Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay",
"bea", "hope", "gay"));
put("bob",
Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea",
"jan", "ivy", "gay"));
put("col",
Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy",
"gay", "cath", "jan"));
put("dan",
Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan",
"bea", "cath", "abi"));
put("ed",
Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi",
"ivy", "hope", "gay"));
put("fred",
Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath",
"jan", "hope", "fay"));
put("gav",
Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee",
"hope", "jan", "fay"));
put("hal",
Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan",
"bea", "gay", "dee"));
put("ian",
Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay",
"ivy", "jan", "eve"));
put("jon",
Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee",
"cath", "ivy", "hope"));
}};
static Map<String, List<String>> girlPrefers =
new HashMap<String, List<String>>(){{
put("abi",
Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan",
"ed", "col", "hal"));
put("bea",
Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian",
"ed", "jon", "hal"));
put("cath",
Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"));
put("dee",
Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav",
"dan", "bob", "ed"));
put("eve",
Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col",
"ed", "ian", "bob"));
put("fay",
Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred",
"gav", "col", "hal"));
put("gay",
Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col",
"ed", "dan", "ian"));
put("hope",
Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal",
"ed", "col", "fred"));
put("ivy",
Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe",
"ed", "jon", "dan"));
put("jan",
Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col",
"ian", "fred", "dan"));
}};
public static void main(String[] args){
Map<String, String> matches = match(guys, guyPrefers, girlPrefers);
for(Map.Entry<String, String> couple:matches.entrySet()){
System.out.println(
couple.getKey() + " is engaged to " + couple.getValue());
}
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
String tmp = matches.get(girls.get(0));
matches.put(girls.get(0), matches.get(girls.get(1)));
matches.put(girls.get(1), tmp);
System.out.println(
girls.get(0) +" and " + girls.get(1) + " have switched partners");
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
}
private static Map<String, String> match(List<String> guys,
Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers){
Map<String, String> engagedTo = new TreeMap<String, String>();
List<String> freeGuys = new LinkedList<String>();
freeGuys.addAll(guys);
while(!freeGuys.isEmpty()){
String thisGuy = freeGuys.remove(0);
List<String> thisGuyPrefers = guyPrefers.get(thisGuy);
for(String girl:thisGuyPrefers){
if(engagedTo.get(girl) == null){
engagedTo.put(girl, thisGuy);
break;
}else{
String otherGuy = engagedTo.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(thisGuy) <
thisGirlPrefers.indexOf(otherGuy)){
engagedTo.put(girl, thisGuy);
freeGuys.add(otherGuy);
break;
}
}
}
}
return engagedTo;
}
private static boolean checkMatches(List<String> guys, List<String> girls,
Map<String, String> matches, Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers) {
if(!matches.keySet().containsAll(girls)){
return false;
}
if(!matches.values().containsAll(guys)){
return false;
}
Map<String, String> invertedMatches = new TreeMap<String, String>();
for(Map.Entry<String, String> couple:matches.entrySet()){
invertedMatches.put(couple.getValue(), couple.getKey());
}
for(Map.Entry<String, String> couple:matches.entrySet()){
List<String> shePrefers = girlPrefers.get(couple.getKey());
List<String> sheLikesBetter = new LinkedList<String>();
sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));
List<String> hePrefers = guyPrefers.get(couple.getValue());
List<String> heLikesBetter = new LinkedList<String>();
heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));
for(String guy : sheLikesBetter){
String guysFinace = invertedMatches.get(guy);
List<String> thisGuyPrefers = guyPrefers.get(guy);
if(thisGuyPrefers.indexOf(guysFinace) >
thisGuyPrefers.indexOf(couple.getKey())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getKey(), guy, couple.getValue(),
guy, couple.getKey());
return false;
}
}
for(String girl : heLikesBetter){
String girlsFinace = matches.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(girlsFinace) >
thisGirlPrefers.indexOf(couple.getValue())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getValue(), girl, couple.getKey(),
girl, couple.getValue());
return false;
}
}
}
return true;
}
}
|
Port the provided Mathematica code into Python while preserving the original functionality. | <<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]
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Convert this Mathematica block to VB, preserving its control flow and logic. | <<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]
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Keep all operations the same but rewrite the snippet in Go. | <<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]
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Please provide an equivalent version of this Nim code in C. | import sequtils, random, strutils
const
Pairs = 10
MNames = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
FNames = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
MPreferences = [
["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"]
]
FPreferences = [
["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"]
]
func getRecPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for r, prefArray in pairs(prefs):
for c, contender in pairs(prefArray):
result[r][c] = prefArray.find(MNames[c])
func getContPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for c, pref_seq in pairs(prefs):
for r, pref in pairs(pref_seq):
result[c][r] = names.find(pref)
const
RecipientPrefs = getRecPreferences(FPreferences, MNames)
ContenderPrefs = getContPreferences(MPreferences, FNames)
proc printCoupleNames(contPairs: seq[int]) =
for c, r in pairs(contPairs):
echo MNames[c] & " 💑 " & FNames[contPairs[c]]
func pair(): (seq[int], seq[int]) =
var
recPairs = newSeqWith(10, -1)
contPairs = newSeqWith(10, -1)
template engage(c, r: int) =
contPairs[c] = r
recPairs[r] = c
var contQueue = newSeqWith(10, 0)
while contPairs.contains(-1):
for c in 0..<Pairs:
if contPairs[c] == -1:
let r = ContenderPrefs[c][contQueue[c]]
contQueue[c] += 1
let curPair = recPairs[r]
if curPair == -1:
engage(c, r)
elif RecipientPrefs[r][c] < RecipientPrefs[r][curPair]:
contPairs[curPair] = -1
engage(c, r)
result = (contPairs, recPairs)
proc randomPair(max: int): (int, int) =
let a = rand(max)
var b = rand(max - 1)
if b == a:
b = max
result = (a, b)
proc perturbPairs(contPairs, recPairs: var seq[int]) =
randomize()
let (a, b) = randomPair(Pairs-1)
echo("Swapping ", MNames[a], " & ", MNames[b], " partners")
swap(contPairs[a], contPairs[b])
swap(recPairs[contPairs[a]], recPairs[contPairs[b]])
proc checkPairStability(contPairs, recPairs: seq[int]): bool =
for c in 0..<Pairs:
let curPairScore = ContenderPrefs[c].find(contPairs[c])
for preferredRec in 0..<curPairScore:
let
checkedRec = ContenderPrefs[c][preferredRec]
curRecPair = recPairs[checkedRec]
if RecipientPrefs[checkedRec][curRecPair] > RecipientPrefs[checkedRec][c]:
echo("💔 ", MNames[c], " prefers ", FNames[checkedRec], " over ", FNames[contPairs[c]])
echo("💔 ", FNames[checkedRec], " prefers ", MNames[c], " over ", MNames[curRecPair])
echo "✗ Unstable"
return false
echo "✓ Stable"
result = true
when isMainModule:
var (contPairs, recPairs) = pair()
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
perturbPairs(contPairs, recPairs)
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Nim. | import sequtils, random, strutils
const
Pairs = 10
MNames = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
FNames = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
MPreferences = [
["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"]
]
FPreferences = [
["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"]
]
func getRecPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for r, prefArray in pairs(prefs):
for c, contender in pairs(prefArray):
result[r][c] = prefArray.find(MNames[c])
func getContPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for c, pref_seq in pairs(prefs):
for r, pref in pairs(pref_seq):
result[c][r] = names.find(pref)
const
RecipientPrefs = getRecPreferences(FPreferences, MNames)
ContenderPrefs = getContPreferences(MPreferences, FNames)
proc printCoupleNames(contPairs: seq[int]) =
for c, r in pairs(contPairs):
echo MNames[c] & " 💑 " & FNames[contPairs[c]]
func pair(): (seq[int], seq[int]) =
var
recPairs = newSeqWith(10, -1)
contPairs = newSeqWith(10, -1)
template engage(c, r: int) =
contPairs[c] = r
recPairs[r] = c
var contQueue = newSeqWith(10, 0)
while contPairs.contains(-1):
for c in 0..<Pairs:
if contPairs[c] == -1:
let r = ContenderPrefs[c][contQueue[c]]
contQueue[c] += 1
let curPair = recPairs[r]
if curPair == -1:
engage(c, r)
elif RecipientPrefs[r][c] < RecipientPrefs[r][curPair]:
contPairs[curPair] = -1
engage(c, r)
result = (contPairs, recPairs)
proc randomPair(max: int): (int, int) =
let a = rand(max)
var b = rand(max - 1)
if b == a:
b = max
result = (a, b)
proc perturbPairs(contPairs, recPairs: var seq[int]) =
randomize()
let (a, b) = randomPair(Pairs-1)
echo("Swapping ", MNames[a], " & ", MNames[b], " partners")
swap(contPairs[a], contPairs[b])
swap(recPairs[contPairs[a]], recPairs[contPairs[b]])
proc checkPairStability(contPairs, recPairs: seq[int]): bool =
for c in 0..<Pairs:
let curPairScore = ContenderPrefs[c].find(contPairs[c])
for preferredRec in 0..<curPairScore:
let
checkedRec = ContenderPrefs[c][preferredRec]
curRecPair = recPairs[checkedRec]
if RecipientPrefs[checkedRec][curRecPair] > RecipientPrefs[checkedRec][c]:
echo("💔 ", MNames[c], " prefers ", FNames[checkedRec], " over ", FNames[contPairs[c]])
echo("💔 ", FNames[checkedRec], " prefers ", MNames[c], " over ", MNames[curRecPair])
echo "✗ Unstable"
return false
echo "✓ Stable"
result = true
when isMainModule:
var (contPairs, recPairs) = pair()
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
perturbPairs(contPairs, recPairs)
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | import sequtils, random, strutils
const
Pairs = 10
MNames = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
FNames = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
MPreferences = [
["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"]
]
FPreferences = [
["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"]
]
func getRecPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for r, prefArray in pairs(prefs):
for c, contender in pairs(prefArray):
result[r][c] = prefArray.find(MNames[c])
func getContPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for c, pref_seq in pairs(prefs):
for r, pref in pairs(pref_seq):
result[c][r] = names.find(pref)
const
RecipientPrefs = getRecPreferences(FPreferences, MNames)
ContenderPrefs = getContPreferences(MPreferences, FNames)
proc printCoupleNames(contPairs: seq[int]) =
for c, r in pairs(contPairs):
echo MNames[c] & " 💑 " & FNames[contPairs[c]]
func pair(): (seq[int], seq[int]) =
var
recPairs = newSeqWith(10, -1)
contPairs = newSeqWith(10, -1)
template engage(c, r: int) =
contPairs[c] = r
recPairs[r] = c
var contQueue = newSeqWith(10, 0)
while contPairs.contains(-1):
for c in 0..<Pairs:
if contPairs[c] == -1:
let r = ContenderPrefs[c][contQueue[c]]
contQueue[c] += 1
let curPair = recPairs[r]
if curPair == -1:
engage(c, r)
elif RecipientPrefs[r][c] < RecipientPrefs[r][curPair]:
contPairs[curPair] = -1
engage(c, r)
result = (contPairs, recPairs)
proc randomPair(max: int): (int, int) =
let a = rand(max)
var b = rand(max - 1)
if b == a:
b = max
result = (a, b)
proc perturbPairs(contPairs, recPairs: var seq[int]) =
randomize()
let (a, b) = randomPair(Pairs-1)
echo("Swapping ", MNames[a], " & ", MNames[b], " partners")
swap(contPairs[a], contPairs[b])
swap(recPairs[contPairs[a]], recPairs[contPairs[b]])
proc checkPairStability(contPairs, recPairs: seq[int]): bool =
for c in 0..<Pairs:
let curPairScore = ContenderPrefs[c].find(contPairs[c])
for preferredRec in 0..<curPairScore:
let
checkedRec = ContenderPrefs[c][preferredRec]
curRecPair = recPairs[checkedRec]
if RecipientPrefs[checkedRec][curRecPair] > RecipientPrefs[checkedRec][c]:
echo("💔 ", MNames[c], " prefers ", FNames[checkedRec], " over ", FNames[contPairs[c]])
echo("💔 ", FNames[checkedRec], " prefers ", MNames[c], " over ", MNames[curRecPair])
echo "✗ Unstable"
return false
echo "✓ Stable"
result = true
when isMainModule:
var (contPairs, recPairs) = pair()
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
perturbPairs(contPairs, recPairs)
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Maintain the same structure and functionality when rewriting this code in Python. | import sequtils, random, strutils
const
Pairs = 10
MNames = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
FNames = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
MPreferences = [
["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"]
]
FPreferences = [
["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"]
]
func getRecPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for r, prefArray in pairs(prefs):
for c, contender in pairs(prefArray):
result[r][c] = prefArray.find(MNames[c])
func getContPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for c, pref_seq in pairs(prefs):
for r, pref in pairs(pref_seq):
result[c][r] = names.find(pref)
const
RecipientPrefs = getRecPreferences(FPreferences, MNames)
ContenderPrefs = getContPreferences(MPreferences, FNames)
proc printCoupleNames(contPairs: seq[int]) =
for c, r in pairs(contPairs):
echo MNames[c] & " 💑 " & FNames[contPairs[c]]
func pair(): (seq[int], seq[int]) =
var
recPairs = newSeqWith(10, -1)
contPairs = newSeqWith(10, -1)
template engage(c, r: int) =
contPairs[c] = r
recPairs[r] = c
var contQueue = newSeqWith(10, 0)
while contPairs.contains(-1):
for c in 0..<Pairs:
if contPairs[c] == -1:
let r = ContenderPrefs[c][contQueue[c]]
contQueue[c] += 1
let curPair = recPairs[r]
if curPair == -1:
engage(c, r)
elif RecipientPrefs[r][c] < RecipientPrefs[r][curPair]:
contPairs[curPair] = -1
engage(c, r)
result = (contPairs, recPairs)
proc randomPair(max: int): (int, int) =
let a = rand(max)
var b = rand(max - 1)
if b == a:
b = max
result = (a, b)
proc perturbPairs(contPairs, recPairs: var seq[int]) =
randomize()
let (a, b) = randomPair(Pairs-1)
echo("Swapping ", MNames[a], " & ", MNames[b], " partners")
swap(contPairs[a], contPairs[b])
swap(recPairs[contPairs[a]], recPairs[contPairs[b]])
proc checkPairStability(contPairs, recPairs: seq[int]): bool =
for c in 0..<Pairs:
let curPairScore = ContenderPrefs[c].find(contPairs[c])
for preferredRec in 0..<curPairScore:
let
checkedRec = ContenderPrefs[c][preferredRec]
curRecPair = recPairs[checkedRec]
if RecipientPrefs[checkedRec][curRecPair] > RecipientPrefs[checkedRec][c]:
echo("💔 ", MNames[c], " prefers ", FNames[checkedRec], " over ", FNames[contPairs[c]])
echo("💔 ", FNames[checkedRec], " prefers ", MNames[c], " over ", MNames[curRecPair])
echo "✗ Unstable"
return false
echo "✓ Stable"
result = true
when isMainModule:
var (contPairs, recPairs) = pair()
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
perturbPairs(contPairs, recPairs)
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Keep all operations the same but rewrite the snippet in VB. | import sequtils, random, strutils
const
Pairs = 10
MNames = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
FNames = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
MPreferences = [
["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"]
]
FPreferences = [
["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"]
]
func getRecPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for r, prefArray in pairs(prefs):
for c, contender in pairs(prefArray):
result[r][c] = prefArray.find(MNames[c])
func getContPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for c, pref_seq in pairs(prefs):
for r, pref in pairs(pref_seq):
result[c][r] = names.find(pref)
const
RecipientPrefs = getRecPreferences(FPreferences, MNames)
ContenderPrefs = getContPreferences(MPreferences, FNames)
proc printCoupleNames(contPairs: seq[int]) =
for c, r in pairs(contPairs):
echo MNames[c] & " 💑 " & FNames[contPairs[c]]
func pair(): (seq[int], seq[int]) =
var
recPairs = newSeqWith(10, -1)
contPairs = newSeqWith(10, -1)
template engage(c, r: int) =
contPairs[c] = r
recPairs[r] = c
var contQueue = newSeqWith(10, 0)
while contPairs.contains(-1):
for c in 0..<Pairs:
if contPairs[c] == -1:
let r = ContenderPrefs[c][contQueue[c]]
contQueue[c] += 1
let curPair = recPairs[r]
if curPair == -1:
engage(c, r)
elif RecipientPrefs[r][c] < RecipientPrefs[r][curPair]:
contPairs[curPair] = -1
engage(c, r)
result = (contPairs, recPairs)
proc randomPair(max: int): (int, int) =
let a = rand(max)
var b = rand(max - 1)
if b == a:
b = max
result = (a, b)
proc perturbPairs(contPairs, recPairs: var seq[int]) =
randomize()
let (a, b) = randomPair(Pairs-1)
echo("Swapping ", MNames[a], " & ", MNames[b], " partners")
swap(contPairs[a], contPairs[b])
swap(recPairs[contPairs[a]], recPairs[contPairs[b]])
proc checkPairStability(contPairs, recPairs: seq[int]): bool =
for c in 0..<Pairs:
let curPairScore = ContenderPrefs[c].find(contPairs[c])
for preferredRec in 0..<curPairScore:
let
checkedRec = ContenderPrefs[c][preferredRec]
curRecPair = recPairs[checkedRec]
if RecipientPrefs[checkedRec][curRecPair] > RecipientPrefs[checkedRec][c]:
echo("💔 ", MNames[c], " prefers ", FNames[checkedRec], " over ", FNames[contPairs[c]])
echo("💔 ", FNames[checkedRec], " prefers ", MNames[c], " over ", MNames[curRecPair])
echo "✗ Unstable"
return false
echo "✓ Stable"
result = true
when isMainModule:
var (contPairs, recPairs) = pair()
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
perturbPairs(contPairs, recPairs)
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Maintain the same structure and functionality when rewriting this code in C. | let men = [
"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"];
]
let women = [
"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"];
]
type woman_name = string
type man_name = string
type man =
{ m_name: man_name;
mutable free: bool;
women_rank: woman_name list;
has_proposed: (woman_name, unit) Hashtbl.t
}
type woman =
{ w_name: woman_name;
men_rank: man_name list;
mutable engaged: man_name option
}
let prefers w m1 m2 =
let rec aux = function
| [] -> invalid_arg "rank_cmp"
| x::_ when x = m1 -> true
| x::_ when x = m2 -> false
| _::xs -> aux xs
in
aux w.men_rank
let take_while f lst =
let rec aux acc = function
| x::xs when f x -> aux (x::acc) xs
| _ -> List.rev acc
in
aux [] lst
let more_ranked_than name =
take_while ((<>) name)
let build_structs ~men ~women =
List.map (fun (name, rank) ->
{ m_name = name;
women_rank = rank;
free = true;
has_proposed = Hashtbl.create 42 }
) men,
List.map (fun (name, rank) ->
{ w_name = name;
men_rank = rank;
engaged = None }
) women
let _stable_matching ms ws =
let men_by_name = Hashtbl.create 42 in
List.iter (fun m -> Hashtbl.add men_by_name m.m_name m) ms;
let women_by_name = Hashtbl.create 42 in
List.iter (fun w -> Hashtbl.add women_by_name w.w_name w) ws;
try
while true do
let m = List.find (fun m -> m.free) ms in
let w_name =
List.find (fun w -> not (Hashtbl.mem m.has_proposed w)) m.women_rank in
Hashtbl.add m.has_proposed w_name ();
let w = Hashtbl.find women_by_name w_name in
match w.engaged with
| None ->
w.engaged <- Some m.m_name;
m.free <- false
| Some m'_name ->
if prefers w m.m_name m'_name
then begin
w.engaged <- Some m.m_name;
let m' = Hashtbl.find men_by_name m'_name in
m'.free <- true;
m.free <- false
end
done;
assert false
with Not_found -> ()
let stable_matching ~men ~women =
let ms, ws = build_structs ~men ~women in
_stable_matching ms ws;
let some = function Some v -> v | None -> "" in
List.map (fun w -> w.w_name, some w.engaged) ws
let is_stable ~men ~women eng =
let ms, ws = build_structs ~men ~women in
not (List.exists (fun (wn, mn) ->
let m = List.find (fun m -> m.m_name = mn) ms in
let prefered_women = more_ranked_than wn m.women_rank in
List.exists (fun pref_w ->
let w = List.find (fun w -> w.w_name = pref_w) ws in
let eng_m = List.assoc pref_w eng in
let prefered_men = more_ranked_than eng_m w.men_rank in
List.mem m.m_name prefered_men
) prefered_women
) eng)
let perturb_engagements eng =
Random.self_init();
let eng = Array.of_list eng in
let len = Array.length eng in
for n = 1 to 3 do
let i = Random.int len
and j = Random.int len in
let w1, m1 = eng.(i)
and w2, m2 = eng.(j) in
eng.(i) <- (w1, m2);
eng.(j) <- (w2, m1);
done;
Array.to_list eng
let print engs =
List.iter (fun (w,m) ->
Printf.printf " %4s is engaged with %s\n" w m) engs;
Printf.printf "# Engagements %s stable\n"
(if is_stable ~men ~women engs then "are" else "are not")
let () =
let engagements = stable_matching ~men ~women in
print engagements;
print_endline "========================";
let engagements = perturb_engagements engagements in
print engagements;
;;
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Translate the given OCaml code snippet into Python without altering its behavior. | let men = [
"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"];
]
let women = [
"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"];
]
type woman_name = string
type man_name = string
type man =
{ m_name: man_name;
mutable free: bool;
women_rank: woman_name list;
has_proposed: (woman_name, unit) Hashtbl.t
}
type woman =
{ w_name: woman_name;
men_rank: man_name list;
mutable engaged: man_name option
}
let prefers w m1 m2 =
let rec aux = function
| [] -> invalid_arg "rank_cmp"
| x::_ when x = m1 -> true
| x::_ when x = m2 -> false
| _::xs -> aux xs
in
aux w.men_rank
let take_while f lst =
let rec aux acc = function
| x::xs when f x -> aux (x::acc) xs
| _ -> List.rev acc
in
aux [] lst
let more_ranked_than name =
take_while ((<>) name)
let build_structs ~men ~women =
List.map (fun (name, rank) ->
{ m_name = name;
women_rank = rank;
free = true;
has_proposed = Hashtbl.create 42 }
) men,
List.map (fun (name, rank) ->
{ w_name = name;
men_rank = rank;
engaged = None }
) women
let _stable_matching ms ws =
let men_by_name = Hashtbl.create 42 in
List.iter (fun m -> Hashtbl.add men_by_name m.m_name m) ms;
let women_by_name = Hashtbl.create 42 in
List.iter (fun w -> Hashtbl.add women_by_name w.w_name w) ws;
try
while true do
let m = List.find (fun m -> m.free) ms in
let w_name =
List.find (fun w -> not (Hashtbl.mem m.has_proposed w)) m.women_rank in
Hashtbl.add m.has_proposed w_name ();
let w = Hashtbl.find women_by_name w_name in
match w.engaged with
| None ->
w.engaged <- Some m.m_name;
m.free <- false
| Some m'_name ->
if prefers w m.m_name m'_name
then begin
w.engaged <- Some m.m_name;
let m' = Hashtbl.find men_by_name m'_name in
m'.free <- true;
m.free <- false
end
done;
assert false
with Not_found -> ()
let stable_matching ~men ~women =
let ms, ws = build_structs ~men ~women in
_stable_matching ms ws;
let some = function Some v -> v | None -> "" in
List.map (fun w -> w.w_name, some w.engaged) ws
let is_stable ~men ~women eng =
let ms, ws = build_structs ~men ~women in
not (List.exists (fun (wn, mn) ->
let m = List.find (fun m -> m.m_name = mn) ms in
let prefered_women = more_ranked_than wn m.women_rank in
List.exists (fun pref_w ->
let w = List.find (fun w -> w.w_name = pref_w) ws in
let eng_m = List.assoc pref_w eng in
let prefered_men = more_ranked_than eng_m w.men_rank in
List.mem m.m_name prefered_men
) prefered_women
) eng)
let perturb_engagements eng =
Random.self_init();
let eng = Array.of_list eng in
let len = Array.length eng in
for n = 1 to 3 do
let i = Random.int len
and j = Random.int len in
let w1, m1 = eng.(i)
and w2, m2 = eng.(j) in
eng.(i) <- (w1, m2);
eng.(j) <- (w2, m1);
done;
Array.to_list eng
let print engs =
List.iter (fun (w,m) ->
Printf.printf " %4s is engaged with %s\n" w m) engs;
Printf.printf "# Engagements %s stable\n"
(if is_stable ~men ~women engs then "are" else "are not")
let () =
let engagements = stable_matching ~men ~women in
print engagements;
print_endline "========================";
let engagements = perturb_engagements engagements in
print engagements;
;;
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Rewrite this program in VB while keeping its functionality equivalent to the OCaml version. | let men = [
"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"];
]
let women = [
"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"];
]
type woman_name = string
type man_name = string
type man =
{ m_name: man_name;
mutable free: bool;
women_rank: woman_name list;
has_proposed: (woman_name, unit) Hashtbl.t
}
type woman =
{ w_name: woman_name;
men_rank: man_name list;
mutable engaged: man_name option
}
let prefers w m1 m2 =
let rec aux = function
| [] -> invalid_arg "rank_cmp"
| x::_ when x = m1 -> true
| x::_ when x = m2 -> false
| _::xs -> aux xs
in
aux w.men_rank
let take_while f lst =
let rec aux acc = function
| x::xs when f x -> aux (x::acc) xs
| _ -> List.rev acc
in
aux [] lst
let more_ranked_than name =
take_while ((<>) name)
let build_structs ~men ~women =
List.map (fun (name, rank) ->
{ m_name = name;
women_rank = rank;
free = true;
has_proposed = Hashtbl.create 42 }
) men,
List.map (fun (name, rank) ->
{ w_name = name;
men_rank = rank;
engaged = None }
) women
let _stable_matching ms ws =
let men_by_name = Hashtbl.create 42 in
List.iter (fun m -> Hashtbl.add men_by_name m.m_name m) ms;
let women_by_name = Hashtbl.create 42 in
List.iter (fun w -> Hashtbl.add women_by_name w.w_name w) ws;
try
while true do
let m = List.find (fun m -> m.free) ms in
let w_name =
List.find (fun w -> not (Hashtbl.mem m.has_proposed w)) m.women_rank in
Hashtbl.add m.has_proposed w_name ();
let w = Hashtbl.find women_by_name w_name in
match w.engaged with
| None ->
w.engaged <- Some m.m_name;
m.free <- false
| Some m'_name ->
if prefers w m.m_name m'_name
then begin
w.engaged <- Some m.m_name;
let m' = Hashtbl.find men_by_name m'_name in
m'.free <- true;
m.free <- false
end
done;
assert false
with Not_found -> ()
let stable_matching ~men ~women =
let ms, ws = build_structs ~men ~women in
_stable_matching ms ws;
let some = function Some v -> v | None -> "" in
List.map (fun w -> w.w_name, some w.engaged) ws
let is_stable ~men ~women eng =
let ms, ws = build_structs ~men ~women in
not (List.exists (fun (wn, mn) ->
let m = List.find (fun m -> m.m_name = mn) ms in
let prefered_women = more_ranked_than wn m.women_rank in
List.exists (fun pref_w ->
let w = List.find (fun w -> w.w_name = pref_w) ws in
let eng_m = List.assoc pref_w eng in
let prefered_men = more_ranked_than eng_m w.men_rank in
List.mem m.m_name prefered_men
) prefered_women
) eng)
let perturb_engagements eng =
Random.self_init();
let eng = Array.of_list eng in
let len = Array.length eng in
for n = 1 to 3 do
let i = Random.int len
and j = Random.int len in
let w1, m1 = eng.(i)
and w2, m2 = eng.(j) in
eng.(i) <- (w1, m2);
eng.(j) <- (w2, m1);
done;
Array.to_list eng
let print engs =
List.iter (fun (w,m) ->
Printf.printf " %4s is engaged with %s\n" w m) engs;
Printf.printf "# Engagements %s stable\n"
(if is_stable ~men ~women engs then "are" else "are not")
let () =
let engagements = stable_matching ~men ~women in
print engagements;
print_endline "========================";
let engagements = perturb_engagements engagements in
print engagements;
;;
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Convert this Perl block to C, preserving its control flow and logic. |
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /],
ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /],
fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /],
gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /],
hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /],
ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /],
jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /],
},
W => {
abi => [qw/ bob fred jon gav ian abe dan ed col hal /],
bea => [qw/ bob abe col fred gav dan ian ed jon hal /],
cath => [qw/ fred bob ed gav hal col ian abe dan jon /],
dee => [qw/ fred jon col abe ian hal gav dan bob ed /],
eve => [qw/ jon hal fred dan abe gav col ed ian bob /],
fay => [qw/ bob abe ed ian jon dan fred gav col hal /],
gay => [qw/ jon gav hal fred bob abe col ed dan ian /],
hope => [qw/ gav jon bob abe ian dan hal ed col fred /],
ivy => [qw/ ian col hal gav fred bob abe ed jon dan /],
jan => [qw/ ed hal gav abe bob jon col ian fred dan /],
},
);
my %Engaged;
my %Proposed;
match_them();
check_stability();
perturb();
check_stability();
sub match_them {
say 'Matchmaking:';
while(my $man = unmatched_man()) {
my $woman = preferred_choice($man);
$Proposed{$man}{$woman} = 1;
if(! $Engaged{W}{$woman}) {
engage($man, $woman);
say "\t$woman and $man";
}
else {
if(woman_prefers($woman, $man)) {
my $engaged_man = $Engaged{W}{$woman};
engage($man, $woman);
undef $Engaged{M}{$engaged_man};
say "\t$woman dumped $engaged_man for $man";
}
}
}
}
sub check_stability {
say 'Stablility:';
my $stable = 1;
foreach my $m (men()) {
foreach my $w (women()) {
if(man_prefers($m, $w) && woman_prefers($w, $m)) {
say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}";
$stable = 0;
}
}
}
if($stable) {
say "\t(all marriages stable)";
}
}
sub unmatched_man {
return first { ! $Engaged{M}{$_} } men();
}
sub preferred_choice {
my $man = shift;
return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };
}
sub engage {
my ($man, $woman) = @_;
$Engaged{W}{$woman} = $man;
$Engaged{M}{$man} = $woman;
}
sub prefers {
my $sex = shift;
return sub {
my ($person, $prospect) = @_;
my $choices = join ' ', @{ $Likes{$sex}{$person} };
return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});
}
}
BEGIN {
*woman_prefers = prefers('W');
*man_prefers = prefers('M');
}
sub perturb {
say 'Perturb:';
say "\tengage abi with fred and bea with jon";
engage('fred' => 'abi');
engage('jon' => 'bea');
}
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } }
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Perl snippet. |
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /],
ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /],
fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /],
gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /],
hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /],
ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /],
jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /],
},
W => {
abi => [qw/ bob fred jon gav ian abe dan ed col hal /],
bea => [qw/ bob abe col fred gav dan ian ed jon hal /],
cath => [qw/ fred bob ed gav hal col ian abe dan jon /],
dee => [qw/ fred jon col abe ian hal gav dan bob ed /],
eve => [qw/ jon hal fred dan abe gav col ed ian bob /],
fay => [qw/ bob abe ed ian jon dan fred gav col hal /],
gay => [qw/ jon gav hal fred bob abe col ed dan ian /],
hope => [qw/ gav jon bob abe ian dan hal ed col fred /],
ivy => [qw/ ian col hal gav fred bob abe ed jon dan /],
jan => [qw/ ed hal gav abe bob jon col ian fred dan /],
},
);
my %Engaged;
my %Proposed;
match_them();
check_stability();
perturb();
check_stability();
sub match_them {
say 'Matchmaking:';
while(my $man = unmatched_man()) {
my $woman = preferred_choice($man);
$Proposed{$man}{$woman} = 1;
if(! $Engaged{W}{$woman}) {
engage($man, $woman);
say "\t$woman and $man";
}
else {
if(woman_prefers($woman, $man)) {
my $engaged_man = $Engaged{W}{$woman};
engage($man, $woman);
undef $Engaged{M}{$engaged_man};
say "\t$woman dumped $engaged_man for $man";
}
}
}
}
sub check_stability {
say 'Stablility:';
my $stable = 1;
foreach my $m (men()) {
foreach my $w (women()) {
if(man_prefers($m, $w) && woman_prefers($w, $m)) {
say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}";
$stable = 0;
}
}
}
if($stable) {
say "\t(all marriages stable)";
}
}
sub unmatched_man {
return first { ! $Engaged{M}{$_} } men();
}
sub preferred_choice {
my $man = shift;
return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };
}
sub engage {
my ($man, $woman) = @_;
$Engaged{W}{$woman} = $man;
$Engaged{M}{$man} = $woman;
}
sub prefers {
my $sex = shift;
return sub {
my ($person, $prospect) = @_;
my $choices = join ' ', @{ $Likes{$sex}{$person} };
return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});
}
}
BEGIN {
*woman_prefers = prefers('W');
*man_prefers = prefers('M');
}
sub perturb {
say 'Perturb:';
say "\tengage abi with fred and bea with jon";
engage('fred' => 'abi');
engage('jon' => 'bea');
}
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } }
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Translate the given Perl code snippet into C++ without altering its behavior. |
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /],
ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /],
fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /],
gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /],
hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /],
ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /],
jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /],
},
W => {
abi => [qw/ bob fred jon gav ian abe dan ed col hal /],
bea => [qw/ bob abe col fred gav dan ian ed jon hal /],
cath => [qw/ fred bob ed gav hal col ian abe dan jon /],
dee => [qw/ fred jon col abe ian hal gav dan bob ed /],
eve => [qw/ jon hal fred dan abe gav col ed ian bob /],
fay => [qw/ bob abe ed ian jon dan fred gav col hal /],
gay => [qw/ jon gav hal fred bob abe col ed dan ian /],
hope => [qw/ gav jon bob abe ian dan hal ed col fred /],
ivy => [qw/ ian col hal gav fred bob abe ed jon dan /],
jan => [qw/ ed hal gav abe bob jon col ian fred dan /],
},
);
my %Engaged;
my %Proposed;
match_them();
check_stability();
perturb();
check_stability();
sub match_them {
say 'Matchmaking:';
while(my $man = unmatched_man()) {
my $woman = preferred_choice($man);
$Proposed{$man}{$woman} = 1;
if(! $Engaged{W}{$woman}) {
engage($man, $woman);
say "\t$woman and $man";
}
else {
if(woman_prefers($woman, $man)) {
my $engaged_man = $Engaged{W}{$woman};
engage($man, $woman);
undef $Engaged{M}{$engaged_man};
say "\t$woman dumped $engaged_man for $man";
}
}
}
}
sub check_stability {
say 'Stablility:';
my $stable = 1;
foreach my $m (men()) {
foreach my $w (women()) {
if(man_prefers($m, $w) && woman_prefers($w, $m)) {
say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}";
$stable = 0;
}
}
}
if($stable) {
say "\t(all marriages stable)";
}
}
sub unmatched_man {
return first { ! $Engaged{M}{$_} } men();
}
sub preferred_choice {
my $man = shift;
return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };
}
sub engage {
my ($man, $woman) = @_;
$Engaged{W}{$woman} = $man;
$Engaged{M}{$man} = $woman;
}
sub prefers {
my $sex = shift;
return sub {
my ($person, $prospect) = @_;
my $choices = join ' ', @{ $Likes{$sex}{$person} };
return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});
}
}
BEGIN {
*woman_prefers = prefers('W');
*man_prefers = prefers('M');
}
sub perturb {
say 'Perturb:';
say "\tengage abi with fred and bea with jon";
engage('fred' => 'abi');
engage('jon' => 'bea');
}
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } }
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Translate the given Perl code snippet into Java without altering its behavior. |
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /],
ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /],
fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /],
gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /],
hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /],
ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /],
jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /],
},
W => {
abi => [qw/ bob fred jon gav ian abe dan ed col hal /],
bea => [qw/ bob abe col fred gav dan ian ed jon hal /],
cath => [qw/ fred bob ed gav hal col ian abe dan jon /],
dee => [qw/ fred jon col abe ian hal gav dan bob ed /],
eve => [qw/ jon hal fred dan abe gav col ed ian bob /],
fay => [qw/ bob abe ed ian jon dan fred gav col hal /],
gay => [qw/ jon gav hal fred bob abe col ed dan ian /],
hope => [qw/ gav jon bob abe ian dan hal ed col fred /],
ivy => [qw/ ian col hal gav fred bob abe ed jon dan /],
jan => [qw/ ed hal gav abe bob jon col ian fred dan /],
},
);
my %Engaged;
my %Proposed;
match_them();
check_stability();
perturb();
check_stability();
sub match_them {
say 'Matchmaking:';
while(my $man = unmatched_man()) {
my $woman = preferred_choice($man);
$Proposed{$man}{$woman} = 1;
if(! $Engaged{W}{$woman}) {
engage($man, $woman);
say "\t$woman and $man";
}
else {
if(woman_prefers($woman, $man)) {
my $engaged_man = $Engaged{W}{$woman};
engage($man, $woman);
undef $Engaged{M}{$engaged_man};
say "\t$woman dumped $engaged_man for $man";
}
}
}
}
sub check_stability {
say 'Stablility:';
my $stable = 1;
foreach my $m (men()) {
foreach my $w (women()) {
if(man_prefers($m, $w) && woman_prefers($w, $m)) {
say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}";
$stable = 0;
}
}
}
if($stable) {
say "\t(all marriages stable)";
}
}
sub unmatched_man {
return first { ! $Engaged{M}{$_} } men();
}
sub preferred_choice {
my $man = shift;
return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };
}
sub engage {
my ($man, $woman) = @_;
$Engaged{W}{$woman} = $man;
$Engaged{M}{$man} = $woman;
}
sub prefers {
my $sex = shift;
return sub {
my ($person, $prospect) = @_;
my $choices = join ' ', @{ $Likes{$sex}{$person} };
return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});
}
}
BEGIN {
*woman_prefers = prefers('W');
*man_prefers = prefers('M');
}
sub perturb {
say 'Perturb:';
say "\tengage abi with fred and bea with jon";
engage('fred' => 'abi');
engage('jon' => 'bea');
}
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } }
| import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"});
static Map<String, List<String>> guyPrefers =
new HashMap<String, List<String>>(){{
put("abe",
Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay",
"bea", "hope", "gay"));
put("bob",
Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea",
"jan", "ivy", "gay"));
put("col",
Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy",
"gay", "cath", "jan"));
put("dan",
Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan",
"bea", "cath", "abi"));
put("ed",
Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi",
"ivy", "hope", "gay"));
put("fred",
Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath",
"jan", "hope", "fay"));
put("gav",
Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee",
"hope", "jan", "fay"));
put("hal",
Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan",
"bea", "gay", "dee"));
put("ian",
Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay",
"ivy", "jan", "eve"));
put("jon",
Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee",
"cath", "ivy", "hope"));
}};
static Map<String, List<String>> girlPrefers =
new HashMap<String, List<String>>(){{
put("abi",
Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan",
"ed", "col", "hal"));
put("bea",
Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian",
"ed", "jon", "hal"));
put("cath",
Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"));
put("dee",
Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav",
"dan", "bob", "ed"));
put("eve",
Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col",
"ed", "ian", "bob"));
put("fay",
Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred",
"gav", "col", "hal"));
put("gay",
Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col",
"ed", "dan", "ian"));
put("hope",
Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal",
"ed", "col", "fred"));
put("ivy",
Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe",
"ed", "jon", "dan"));
put("jan",
Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col",
"ian", "fred", "dan"));
}};
public static void main(String[] args){
Map<String, String> matches = match(guys, guyPrefers, girlPrefers);
for(Map.Entry<String, String> couple:matches.entrySet()){
System.out.println(
couple.getKey() + " is engaged to " + couple.getValue());
}
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
String tmp = matches.get(girls.get(0));
matches.put(girls.get(0), matches.get(girls.get(1)));
matches.put(girls.get(1), tmp);
System.out.println(
girls.get(0) +" and " + girls.get(1) + " have switched partners");
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
}
private static Map<String, String> match(List<String> guys,
Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers){
Map<String, String> engagedTo = new TreeMap<String, String>();
List<String> freeGuys = new LinkedList<String>();
freeGuys.addAll(guys);
while(!freeGuys.isEmpty()){
String thisGuy = freeGuys.remove(0);
List<String> thisGuyPrefers = guyPrefers.get(thisGuy);
for(String girl:thisGuyPrefers){
if(engagedTo.get(girl) == null){
engagedTo.put(girl, thisGuy);
break;
}else{
String otherGuy = engagedTo.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(thisGuy) <
thisGirlPrefers.indexOf(otherGuy)){
engagedTo.put(girl, thisGuy);
freeGuys.add(otherGuy);
break;
}
}
}
}
return engagedTo;
}
private static boolean checkMatches(List<String> guys, List<String> girls,
Map<String, String> matches, Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers) {
if(!matches.keySet().containsAll(girls)){
return false;
}
if(!matches.values().containsAll(guys)){
return false;
}
Map<String, String> invertedMatches = new TreeMap<String, String>();
for(Map.Entry<String, String> couple:matches.entrySet()){
invertedMatches.put(couple.getValue(), couple.getKey());
}
for(Map.Entry<String, String> couple:matches.entrySet()){
List<String> shePrefers = girlPrefers.get(couple.getKey());
List<String> sheLikesBetter = new LinkedList<String>();
sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));
List<String> hePrefers = guyPrefers.get(couple.getValue());
List<String> heLikesBetter = new LinkedList<String>();
heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));
for(String guy : sheLikesBetter){
String guysFinace = invertedMatches.get(guy);
List<String> thisGuyPrefers = guyPrefers.get(guy);
if(thisGuyPrefers.indexOf(guysFinace) >
thisGuyPrefers.indexOf(couple.getKey())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getKey(), guy, couple.getValue(),
guy, couple.getKey());
return false;
}
}
for(String girl : heLikesBetter){
String girlsFinace = matches.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(girlsFinace) >
thisGirlPrefers.indexOf(couple.getValue())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getValue(), girl, couple.getKey(),
girl, couple.getValue());
return false;
}
}
}
return true;
}
}
|
Ensure the translated Python code behaves exactly like the original Perl snippet. |
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /],
ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /],
fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /],
gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /],
hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /],
ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /],
jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /],
},
W => {
abi => [qw/ bob fred jon gav ian abe dan ed col hal /],
bea => [qw/ bob abe col fred gav dan ian ed jon hal /],
cath => [qw/ fred bob ed gav hal col ian abe dan jon /],
dee => [qw/ fred jon col abe ian hal gav dan bob ed /],
eve => [qw/ jon hal fred dan abe gav col ed ian bob /],
fay => [qw/ bob abe ed ian jon dan fred gav col hal /],
gay => [qw/ jon gav hal fred bob abe col ed dan ian /],
hope => [qw/ gav jon bob abe ian dan hal ed col fred /],
ivy => [qw/ ian col hal gav fred bob abe ed jon dan /],
jan => [qw/ ed hal gav abe bob jon col ian fred dan /],
},
);
my %Engaged;
my %Proposed;
match_them();
check_stability();
perturb();
check_stability();
sub match_them {
say 'Matchmaking:';
while(my $man = unmatched_man()) {
my $woman = preferred_choice($man);
$Proposed{$man}{$woman} = 1;
if(! $Engaged{W}{$woman}) {
engage($man, $woman);
say "\t$woman and $man";
}
else {
if(woman_prefers($woman, $man)) {
my $engaged_man = $Engaged{W}{$woman};
engage($man, $woman);
undef $Engaged{M}{$engaged_man};
say "\t$woman dumped $engaged_man for $man";
}
}
}
}
sub check_stability {
say 'Stablility:';
my $stable = 1;
foreach my $m (men()) {
foreach my $w (women()) {
if(man_prefers($m, $w) && woman_prefers($w, $m)) {
say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}";
$stable = 0;
}
}
}
if($stable) {
say "\t(all marriages stable)";
}
}
sub unmatched_man {
return first { ! $Engaged{M}{$_} } men();
}
sub preferred_choice {
my $man = shift;
return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };
}
sub engage {
my ($man, $woman) = @_;
$Engaged{W}{$woman} = $man;
$Engaged{M}{$man} = $woman;
}
sub prefers {
my $sex = shift;
return sub {
my ($person, $prospect) = @_;
my $choices = join ' ', @{ $Likes{$sex}{$person} };
return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});
}
}
BEGIN {
*woman_prefers = prefers('W');
*man_prefers = prefers('M');
}
sub perturb {
say 'Perturb:';
say "\tengage abi with fred and bea with jon";
engage('fred' => 'abi');
engage('jon' => 'bea');
}
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } }
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Generate an equivalent VB version of this Perl code. |
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /],
ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /],
fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /],
gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /],
hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /],
ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /],
jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /],
},
W => {
abi => [qw/ bob fred jon gav ian abe dan ed col hal /],
bea => [qw/ bob abe col fred gav dan ian ed jon hal /],
cath => [qw/ fred bob ed gav hal col ian abe dan jon /],
dee => [qw/ fred jon col abe ian hal gav dan bob ed /],
eve => [qw/ jon hal fred dan abe gav col ed ian bob /],
fay => [qw/ bob abe ed ian jon dan fred gav col hal /],
gay => [qw/ jon gav hal fred bob abe col ed dan ian /],
hope => [qw/ gav jon bob abe ian dan hal ed col fred /],
ivy => [qw/ ian col hal gav fred bob abe ed jon dan /],
jan => [qw/ ed hal gav abe bob jon col ian fred dan /],
},
);
my %Engaged;
my %Proposed;
match_them();
check_stability();
perturb();
check_stability();
sub match_them {
say 'Matchmaking:';
while(my $man = unmatched_man()) {
my $woman = preferred_choice($man);
$Proposed{$man}{$woman} = 1;
if(! $Engaged{W}{$woman}) {
engage($man, $woman);
say "\t$woman and $man";
}
else {
if(woman_prefers($woman, $man)) {
my $engaged_man = $Engaged{W}{$woman};
engage($man, $woman);
undef $Engaged{M}{$engaged_man};
say "\t$woman dumped $engaged_man for $man";
}
}
}
}
sub check_stability {
say 'Stablility:';
my $stable = 1;
foreach my $m (men()) {
foreach my $w (women()) {
if(man_prefers($m, $w) && woman_prefers($w, $m)) {
say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}";
$stable = 0;
}
}
}
if($stable) {
say "\t(all marriages stable)";
}
}
sub unmatched_man {
return first { ! $Engaged{M}{$_} } men();
}
sub preferred_choice {
my $man = shift;
return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };
}
sub engage {
my ($man, $woman) = @_;
$Engaged{W}{$woman} = $man;
$Engaged{M}{$man} = $woman;
}
sub prefers {
my $sex = shift;
return sub {
my ($person, $prospect) = @_;
my $choices = join ' ', @{ $Likes{$sex}{$person} };
return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});
}
}
BEGIN {
*woman_prefers = prefers('W');
*man_prefers = prefers('M');
}
sub perturb {
say 'Perturb:';
say "\tengage abi with fred and bea with jon";
engage('fred' => 'abi');
engage('jon' => 'bea');
}
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } }
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Produce a language-to-language conversion: from Perl to Go, same semantics. |
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /],
ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /],
fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /],
gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /],
hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /],
ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /],
jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /],
},
W => {
abi => [qw/ bob fred jon gav ian abe dan ed col hal /],
bea => [qw/ bob abe col fred gav dan ian ed jon hal /],
cath => [qw/ fred bob ed gav hal col ian abe dan jon /],
dee => [qw/ fred jon col abe ian hal gav dan bob ed /],
eve => [qw/ jon hal fred dan abe gav col ed ian bob /],
fay => [qw/ bob abe ed ian jon dan fred gav col hal /],
gay => [qw/ jon gav hal fred bob abe col ed dan ian /],
hope => [qw/ gav jon bob abe ian dan hal ed col fred /],
ivy => [qw/ ian col hal gav fred bob abe ed jon dan /],
jan => [qw/ ed hal gav abe bob jon col ian fred dan /],
},
);
my %Engaged;
my %Proposed;
match_them();
check_stability();
perturb();
check_stability();
sub match_them {
say 'Matchmaking:';
while(my $man = unmatched_man()) {
my $woman = preferred_choice($man);
$Proposed{$man}{$woman} = 1;
if(! $Engaged{W}{$woman}) {
engage($man, $woman);
say "\t$woman and $man";
}
else {
if(woman_prefers($woman, $man)) {
my $engaged_man = $Engaged{W}{$woman};
engage($man, $woman);
undef $Engaged{M}{$engaged_man};
say "\t$woman dumped $engaged_man for $man";
}
}
}
}
sub check_stability {
say 'Stablility:';
my $stable = 1;
foreach my $m (men()) {
foreach my $w (women()) {
if(man_prefers($m, $w) && woman_prefers($w, $m)) {
say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}";
$stable = 0;
}
}
}
if($stable) {
say "\t(all marriages stable)";
}
}
sub unmatched_man {
return first { ! $Engaged{M}{$_} } men();
}
sub preferred_choice {
my $man = shift;
return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };
}
sub engage {
my ($man, $woman) = @_;
$Engaged{W}{$woman} = $man;
$Engaged{M}{$man} = $woman;
}
sub prefers {
my $sex = shift;
return sub {
my ($person, $prospect) = @_;
my $choices = join ' ', @{ $Likes{$sex}{$person} };
return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});
}
}
BEGIN {
*woman_prefers = prefers('W');
*man_prefers = prefers('M');
}
sub perturb {
say 'Perturb:';
say "\tengage abi with fred and bea with jon";
engage('fred' => 'abi');
engage('jon' => 'bea');
}
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } }
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Convert this PowerShell snippet to VB and keep its semantics consistent. | using namespace System.Collections.Generic
$ErrorActionPreference = 'Stop'
class Person{
hidden [int] $_candidateIndex;
[string] $Name
[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()
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Translate this program into C but keep the logic exactly as in Racket. | #lang racket
(define MEN
'([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]))
(define WOMEN
'([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 ]))
(define (better? x y l) (memq y (cdr (memq x l))))
(define (stable-matching Mprefs Wprefs)
(define M (map car Mprefs))
(define engagements (make-hasheq))
(define preferences (make-hasheq))
(define (engage! m w)
(hash-set! engagements m w)
(hash-set! engagements w m))
(for ([m Mprefs]) (hash-set! preferences (car m) (cdr m)))
(for ([w Wprefs]) (hash-set! preferences (car w) (cdr w)))
(let loop ()
(define m+w
(for/or ([m M])
(and (not (hash-ref engagements m #f))
(let ([p (hash-ref preferences m)])
(and (pair? p)
(let ([w (car p)])
(hash-set! preferences m (cdr p))
(cons m w)))))))
(when m+w
(define m (car m+w))
(define w (cdr m+w))
(define m* (hash-ref engagements w #f))
(cond [(not m*) (engage! m w)]
[(better? m m* (hash-ref preferences w))
(engage! m w)
(hash-set! engagements m* #f)])
(loop)))
engagements)
(define (find-unstable Mprefs Wprefs matches)
(for*/or ([m (map car Mprefs)] [w (map car Wprefs)])
(define w* (hash-ref matches m))
(define m* (hash-ref matches w))
(and (not (eq? m m*))
(better? w w* (cdr (assq m Mprefs)))
(better? m m* (cdr (assq w Wprefs)))
(cons m w))))
(define (check-stability)
(let ([u (find-unstable MEN WOMEN matches)])
(if u
(printf "Unstable: ~a and ~a prefer each other over partners.\n"
(car u) (cdr u))
(printf "The match is stable.\n"))))
(define matches (stable-matching MEN WOMEN))
(printf "Found matches:\n")
(for ([m (map car MEN)]) (printf " ~a, ~a\n" m (hash-ref matches m)))
(check-stability)
(let ([M (map car (take (shuffle MEN) 2))])
(printf "Swapping wives of ~a and ~a\n" (car M) (cadr M))
(define (swap! x y)
(define t (hash-ref matches x))
(hash-set! matches x (hash-ref matches y))
(hash-set! matches y t))
(swap! (car M) (cadr M))
(swap! (hash-ref matches (car M)) (hash-ref matches (cadr M))))
(check-stability)
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Produce a language-to-language conversion: from Racket to C#, same semantics. | #lang racket
(define MEN
'([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]))
(define WOMEN
'([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 ]))
(define (better? x y l) (memq y (cdr (memq x l))))
(define (stable-matching Mprefs Wprefs)
(define M (map car Mprefs))
(define engagements (make-hasheq))
(define preferences (make-hasheq))
(define (engage! m w)
(hash-set! engagements m w)
(hash-set! engagements w m))
(for ([m Mprefs]) (hash-set! preferences (car m) (cdr m)))
(for ([w Wprefs]) (hash-set! preferences (car w) (cdr w)))
(let loop ()
(define m+w
(for/or ([m M])
(and (not (hash-ref engagements m #f))
(let ([p (hash-ref preferences m)])
(and (pair? p)
(let ([w (car p)])
(hash-set! preferences m (cdr p))
(cons m w)))))))
(when m+w
(define m (car m+w))
(define w (cdr m+w))
(define m* (hash-ref engagements w #f))
(cond [(not m*) (engage! m w)]
[(better? m m* (hash-ref preferences w))
(engage! m w)
(hash-set! engagements m* #f)])
(loop)))
engagements)
(define (find-unstable Mprefs Wprefs matches)
(for*/or ([m (map car Mprefs)] [w (map car Wprefs)])
(define w* (hash-ref matches m))
(define m* (hash-ref matches w))
(and (not (eq? m m*))
(better? w w* (cdr (assq m Mprefs)))
(better? m m* (cdr (assq w Wprefs)))
(cons m w))))
(define (check-stability)
(let ([u (find-unstable MEN WOMEN matches)])
(if u
(printf "Unstable: ~a and ~a prefer each other over partners.\n"
(car u) (cdr u))
(printf "The match is stable.\n"))))
(define matches (stable-matching MEN WOMEN))
(printf "Found matches:\n")
(for ([m (map car MEN)]) (printf " ~a, ~a\n" m (hash-ref matches m)))
(check-stability)
(let ([M (map car (take (shuffle MEN) 2))])
(printf "Swapping wives of ~a and ~a\n" (car M) (cadr M))
(define (swap! x y)
(define t (hash-ref matches x))
(hash-set! matches x (hash-ref matches y))
(hash-set! matches y t))
(swap! (car M) (cadr M))
(swap! (hash-ref matches (car M)) (hash-ref matches (cadr M))))
(check-stability)
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Produce a functionally identical C++ code for the snippet given in Racket. | #lang racket
(define MEN
'([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]))
(define WOMEN
'([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 ]))
(define (better? x y l) (memq y (cdr (memq x l))))
(define (stable-matching Mprefs Wprefs)
(define M (map car Mprefs))
(define engagements (make-hasheq))
(define preferences (make-hasheq))
(define (engage! m w)
(hash-set! engagements m w)
(hash-set! engagements w m))
(for ([m Mprefs]) (hash-set! preferences (car m) (cdr m)))
(for ([w Wprefs]) (hash-set! preferences (car w) (cdr w)))
(let loop ()
(define m+w
(for/or ([m M])
(and (not (hash-ref engagements m #f))
(let ([p (hash-ref preferences m)])
(and (pair? p)
(let ([w (car p)])
(hash-set! preferences m (cdr p))
(cons m w)))))))
(when m+w
(define m (car m+w))
(define w (cdr m+w))
(define m* (hash-ref engagements w #f))
(cond [(not m*) (engage! m w)]
[(better? m m* (hash-ref preferences w))
(engage! m w)
(hash-set! engagements m* #f)])
(loop)))
engagements)
(define (find-unstable Mprefs Wprefs matches)
(for*/or ([m (map car Mprefs)] [w (map car Wprefs)])
(define w* (hash-ref matches m))
(define m* (hash-ref matches w))
(and (not (eq? m m*))
(better? w w* (cdr (assq m Mprefs)))
(better? m m* (cdr (assq w Wprefs)))
(cons m w))))
(define (check-stability)
(let ([u (find-unstable MEN WOMEN matches)])
(if u
(printf "Unstable: ~a and ~a prefer each other over partners.\n"
(car u) (cdr u))
(printf "The match is stable.\n"))))
(define matches (stable-matching MEN WOMEN))
(printf "Found matches:\n")
(for ([m (map car MEN)]) (printf " ~a, ~a\n" m (hash-ref matches m)))
(check-stability)
(let ([M (map car (take (shuffle MEN) 2))])
(printf "Swapping wives of ~a and ~a\n" (car M) (cadr M))
(define (swap! x y)
(define t (hash-ref matches x))
(hash-set! matches x (hash-ref matches y))
(hash-set! matches y t))
(swap! (car M) (cadr M))
(swap! (hash-ref matches (car M)) (hash-ref matches (cadr M))))
(check-stability)
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Write the same algorithm in Python as shown in this Racket implementation. | #lang racket
(define MEN
'([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]))
(define WOMEN
'([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 ]))
(define (better? x y l) (memq y (cdr (memq x l))))
(define (stable-matching Mprefs Wprefs)
(define M (map car Mprefs))
(define engagements (make-hasheq))
(define preferences (make-hasheq))
(define (engage! m w)
(hash-set! engagements m w)
(hash-set! engagements w m))
(for ([m Mprefs]) (hash-set! preferences (car m) (cdr m)))
(for ([w Wprefs]) (hash-set! preferences (car w) (cdr w)))
(let loop ()
(define m+w
(for/or ([m M])
(and (not (hash-ref engagements m #f))
(let ([p (hash-ref preferences m)])
(and (pair? p)
(let ([w (car p)])
(hash-set! preferences m (cdr p))
(cons m w)))))))
(when m+w
(define m (car m+w))
(define w (cdr m+w))
(define m* (hash-ref engagements w #f))
(cond [(not m*) (engage! m w)]
[(better? m m* (hash-ref preferences w))
(engage! m w)
(hash-set! engagements m* #f)])
(loop)))
engagements)
(define (find-unstable Mprefs Wprefs matches)
(for*/or ([m (map car Mprefs)] [w (map car Wprefs)])
(define w* (hash-ref matches m))
(define m* (hash-ref matches w))
(and (not (eq? m m*))
(better? w w* (cdr (assq m Mprefs)))
(better? m m* (cdr (assq w Wprefs)))
(cons m w))))
(define (check-stability)
(let ([u (find-unstable MEN WOMEN matches)])
(if u
(printf "Unstable: ~a and ~a prefer each other over partners.\n"
(car u) (cdr u))
(printf "The match is stable.\n"))))
(define matches (stable-matching MEN WOMEN))
(printf "Found matches:\n")
(for ([m (map car MEN)]) (printf " ~a, ~a\n" m (hash-ref matches m)))
(check-stability)
(let ([M (map car (take (shuffle MEN) 2))])
(printf "Swapping wives of ~a and ~a\n" (car M) (cadr M))
(define (swap! x y)
(define t (hash-ref matches x))
(hash-set! matches x (hash-ref matches y))
(hash-set! matches y t))
(swap! (car M) (cadr M))
(swap! (hash-ref matches (car M)) (hash-ref matches (cadr M))))
(check-stability)
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Convert the following code from Racket to VB, ensuring the logic remains intact. | #lang racket
(define MEN
'([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]))
(define WOMEN
'([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 ]))
(define (better? x y l) (memq y (cdr (memq x l))))
(define (stable-matching Mprefs Wprefs)
(define M (map car Mprefs))
(define engagements (make-hasheq))
(define preferences (make-hasheq))
(define (engage! m w)
(hash-set! engagements m w)
(hash-set! engagements w m))
(for ([m Mprefs]) (hash-set! preferences (car m) (cdr m)))
(for ([w Wprefs]) (hash-set! preferences (car w) (cdr w)))
(let loop ()
(define m+w
(for/or ([m M])
(and (not (hash-ref engagements m #f))
(let ([p (hash-ref preferences m)])
(and (pair? p)
(let ([w (car p)])
(hash-set! preferences m (cdr p))
(cons m w)))))))
(when m+w
(define m (car m+w))
(define w (cdr m+w))
(define m* (hash-ref engagements w #f))
(cond [(not m*) (engage! m w)]
[(better? m m* (hash-ref preferences w))
(engage! m w)
(hash-set! engagements m* #f)])
(loop)))
engagements)
(define (find-unstable Mprefs Wprefs matches)
(for*/or ([m (map car Mprefs)] [w (map car Wprefs)])
(define w* (hash-ref matches m))
(define m* (hash-ref matches w))
(and (not (eq? m m*))
(better? w w* (cdr (assq m Mprefs)))
(better? m m* (cdr (assq w Wprefs)))
(cons m w))))
(define (check-stability)
(let ([u (find-unstable MEN WOMEN matches)])
(if u
(printf "Unstable: ~a and ~a prefer each other over partners.\n"
(car u) (cdr u))
(printf "The match is stable.\n"))))
(define matches (stable-matching MEN WOMEN))
(printf "Found matches:\n")
(for ([m (map car MEN)]) (printf " ~a, ~a\n" m (hash-ref matches m)))
(check-stability)
(let ([M (map car (take (shuffle MEN) 2))])
(printf "Swapping wives of ~a and ~a\n" (car M) (cadr M))
(define (swap! x y)
(define t (hash-ref matches x))
(hash-set! matches x (hash-ref matches y))
(hash-set! matches y t))
(swap! (car M) (cadr M))
(swap! (hash-ref matches (car M)) (hash-ref matches (cadr M))))
(check-stability)
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Port the following code from Racket to Go with equivalent syntax and logic. | #lang racket
(define MEN
'([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]))
(define WOMEN
'([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 ]))
(define (better? x y l) (memq y (cdr (memq x l))))
(define (stable-matching Mprefs Wprefs)
(define M (map car Mprefs))
(define engagements (make-hasheq))
(define preferences (make-hasheq))
(define (engage! m w)
(hash-set! engagements m w)
(hash-set! engagements w m))
(for ([m Mprefs]) (hash-set! preferences (car m) (cdr m)))
(for ([w Wprefs]) (hash-set! preferences (car w) (cdr w)))
(let loop ()
(define m+w
(for/or ([m M])
(and (not (hash-ref engagements m #f))
(let ([p (hash-ref preferences m)])
(and (pair? p)
(let ([w (car p)])
(hash-set! preferences m (cdr p))
(cons m w)))))))
(when m+w
(define m (car m+w))
(define w (cdr m+w))
(define m* (hash-ref engagements w #f))
(cond [(not m*) (engage! m w)]
[(better? m m* (hash-ref preferences w))
(engage! m w)
(hash-set! engagements m* #f)])
(loop)))
engagements)
(define (find-unstable Mprefs Wprefs matches)
(for*/or ([m (map car Mprefs)] [w (map car Wprefs)])
(define w* (hash-ref matches m))
(define m* (hash-ref matches w))
(and (not (eq? m m*))
(better? w w* (cdr (assq m Mprefs)))
(better? m m* (cdr (assq w Wprefs)))
(cons m w))))
(define (check-stability)
(let ([u (find-unstable MEN WOMEN matches)])
(if u
(printf "Unstable: ~a and ~a prefer each other over partners.\n"
(car u) (cdr u))
(printf "The match is stable.\n"))))
(define matches (stable-matching MEN WOMEN))
(printf "Found matches:\n")
(for ([m (map car MEN)]) (printf " ~a, ~a\n" m (hash-ref matches m)))
(check-stability)
(let ([M (map car (take (shuffle MEN) 2))])
(printf "Swapping wives of ~a and ~a\n" (car M) (cadr M))
(define (swap! x y)
(define t (hash-ref matches x))
(hash-set! matches x (hash-ref matches y))
(hash-set! matches y t))
(swap! (car M) (cadr M))
(swap! (hash-ref matches (car M)) (hash-ref matches (cadr M))))
(check-stability)
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Write the same algorithm in VB as shown in this REXX implementation. |
* pref.b Preferences of boy b
* pref.g Preferences of girl g
* boys List of boys
* girls List of girls
* plist List of proposals
* mlist List of (current) matches
* glist List of girls to be matched
* glist.b List of girls that proposed to boy b
* blen maximum length of boys' names
* glen maximum length of girls' names
---------------------------------------------------------------------*/
pref.Charlotte=translate('Bingley Darcy Collins Wickham ')
pref.Elisabeth=translate('Wickham Darcy Bingley Collins ')
pref.Jane =translate('Bingley Wickham Darcy Collins ')
pref.Lydia =translate('Bingley Wickham Darcy Collins ')
pref.Bingley =translate('Jane Elisabeth Lydia Charlotte')
pref.Collins =translate('Jane Elisabeth Lydia Charlotte')
pref.Darcy =translate('Elisabeth Jane Charlotte Lydia')
pref.Wickham =translate('Lydia Jane Elisabeth Charlotte')
pref.ABE='ABI EVE CATH IVY JAN DEE FAY BEA HOPE GAY'
pref.BOB='CATH HOPE ABI DEE EVE FAY BEA JAN IVY GAY'
pref.COL='HOPE EVE ABI DEE BEA FAY IVY GAY CATH JAN'
pref.DAN='IVY FAY DEE GAY HOPE EVE JAN BEA CATH ABI'
pref.ED='JAN DEE BEA CATH FAY EVE ABI IVY HOPE GAY'
pref.FRED='BEA ABI DEE GAY EVE IVY CATH JAN HOPE FAY'
pref.GAV='GAY EVE IVY BEA CATH ABI DEE HOPE JAN FAY'
pref.HAL='ABI EVE HOPE FAY IVY CATH JAN BEA GAY DEE'
pref.IAN='HOPE CATH DEE GAY BEA ABI FAY IVY JAN EVE'
pref.JON='ABI FAY JAN GAY EVE BEA DEE CATH IVY HOPE'
pref.ABI='BOB FRED JON GAV IAN ABE DAN ED COL HAL'
pref.BEA='BOB ABE COL FRED GAV DAN IAN ED JON HAL'
pref.CATH='FRED BOB ED GAV HAL COL IAN ABE DAN JON'
pref.DEE='FRED JON COL ABE IAN HAL GAV DAN BOB ED'
pref.EVE='JON HAL FRED DAN ABE GAV COL ED IAN BOB'
pref.FAY='BOB ABE ED IAN JON DAN FRED GAV COL HAL'
pref.GAY='JON GAV HAL FRED BOB ABE COL ED DAN IAN'
pref.HOPE='GAV JON BOB ABE IAN DAN HAL ED COL FRED'
pref.IVY='IAN COL HAL GAV FRED BOB ABE ED JON DAN'
pref.JAN='ED HAL GAV ABE BOB JON COL IAN FRED DAN'
If arg(1)>'' Then Do
Say 'Input from task description'
boys='ABE BOB COL DAN ED FRED GAV HAL IAN JON'
girls='ABI BEA CATH DEE EVE FAY GAY HOPE IVY JAN'
End
Else Do
Say 'Input from link'
girls=translate('Charlotte Elisabeth Jane Lydia')
boys =translate('Bingley Collins Darcy Wickham')
End
debug=0
blen=0
Do i=1 To words(boys)
blen=max(blen,length(word(boys,i)))
End
glen=0
Do i=1 To words(girls)
glen=max(glen,length(word(girls,i)))
End
glist=girls
mlist=''
Do ri=1 By 1 Until glist=''
Call dbg 'Round' ri
plist=''
glist.=''
Do gi=1 To words(glist)
gg=word(glist,gi)
b=word(pref.gg,1)
plist=plist gg'-'||b
glist.b=glist.b gg
Call dbg left(gg,glen) 'proposes to' b
End
Do bi=1 To words(boys)
b=word(boys,bi)
If glist.b>'' Then
Call dbg b 'has these proposals' glist.b
End
Do bi=1 To words(boys)
b=word(boys,bi)
bm=pos(b'*',mlist)
Select
When words(glist.b)=1 Then Do
gg=word(glist.b,1)
If bm=0 Then Do
Call dbg b 'accepts' gg
Call set_mlist 'A',mlist b||'*'||gg
Call set_glist 'A',remove(gg,glist)
pref.gg=remove(b,pref.gg)
End
Else Do
Parse Var mlist =(bm) '*' go ' '
If wordpos(gg,pref.b)<wordpos(go,pref.b) Then Do
Call set_mlist 'B',repl(mlist,b||'*'||gg,b||'*'||go)
Call dbg b 'releases' go
Call dbg b 'accepts ' gg
Call set_glist 'B',glist go
Call set_glist 'C',remove(gg,glist)
End
pref.gg=remove(b,pref.gg)
End
End
When words(glist.b)>1 Then
Call pick_1
Otherwise Nop
End
End
Call dbg 'Matches :' mlist
Call dbg 'free girls:' glist
Call check 'L'
End
Say 'Success at round' (ri-1)
Do While mlist>''
Parse Var mlist boy '*' girl mlist
Say left(boy,blen) 'matches' girl
End
Exit
pick_1:
If bm>0 Then Do
Parse Var mlist =(bm) '*' go ' '
pmin=wordpos(go,pref.b)
End
Else Do
go=''
pmin=99
End
Do gi=1 To words(glist.b)
gt=word(glist.b,gi)
gp=wordpos(gt,pref.b)
If gp<pmin Then Do
pmin=gp
gg=gt
End
End
If bm=0 Then Do
Call dbg b 'accepts' gg
Call set_mlist 'A',mlist b||'*'||gg
Call set_glist 'A',remove(gg,glist)
pref.gg=remove(b,pref.gg)
End
Else Do
If gg<>go Then Do
Call set_mlist 'B',repl(mlist,b||'*'||gg,b||'*'||go)
Call dbg b 'releases' go
Call dbg b 'accepts ' gg
Call set_glist 'B',glist go
Call set_glist 'C',remove(gg,glist)
pref.gg=remove(b,pref.gg)
End
End
Return
remove:
Parse Arg needle,haystack
pp=pos(needle,haystack)
If pp>0 Then
res=left(haystack,pp-1) substr(haystack,pp+length(needle))
Else
res=haystack
Return space(res)
set_mlist:
Parse Arg where,new_mlist
Call dbg 'set_mlist' where':' mlist
mlist=space(new_mlist)
Call dbg 'set_mlist ->' mlist
Call dbg ''
Return
set_glist:
Parse Arg where,new_glist
Call dbg 'set_glist' where':' glist
glist=new_glist
Call dbg 'set_glist ->' glist
Call dbg ''
Return
check:
If words(mlist)+words(glist)<>words(boys) Then Do
Call dbg 'FEHLER bei' arg(1) (words(mlist)+words(glist))'<>10'
say 'match='mlist'<'
say ' glist='glist'<'
End
Return
dbg:
If debug Then
Call dbg arg(1)
Return
repl: Procedure
Parse Arg s,new,old
Do i=1 To 100 Until p=0
p=pos(old,s)
If p>0 Then
s=left(s,p-1)||new||substr(s,p+length(old))
End
Return s
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Rewrite the snippet below in C so it works the same as the original Ruby code. | class Person
def initialize(name)
@name = name
@fiance = nil
@preferences = []
@proposals = []
end
attr_reader :name, :proposals
attr_accessor :fiance, :preferences
def to_s
@name
end
def free
@fiance = nil
end
def single?
@fiance == nil
end
def engage(person)
self.fiance = person
person.fiance = self
end
def better_choice?(person)
@preferences.index(person) < @preferences.index(@fiance)
end
def propose_to(person)
puts "
@proposals << person
person.respond_to_proposal_from(self)
end
def respond_to_proposal_from(person)
if single?
puts "
engage(person)
elsif better_choice?(person)
puts "
@fiance.free
engage(person)
else
puts "
end
end
end
prefs = {
'abe' => %w[abi eve cath ivy jan dee fay bea hope gay],
'bob' => %w[cath hope abi dee eve fay bea jan ivy gay],
'col' => %w[hope eve abi dee bea fay ivy gay cath jan],
'dan' => %w[ivy fay dee gay hope eve jan bea cath abi],
'ed' => %w[jan dee bea cath fay eve abi ivy hope gay],
'fred' => %w[bea abi dee gay eve ivy cath jan hope fay],
'gav' => %w[gay eve ivy bea cath abi dee hope jan fay],
'hal' => %w[abi eve hope fay ivy cath jan bea gay dee],
'ian' => %w[hope cath dee gay bea abi fay ivy jan eve],
'jon' => %w[abi fay jan gay eve bea dee cath ivy hope],
'abi' => %w[bob fred jon gav ian abe dan ed col hal],
'bea' => %w[bob abe col fred gav dan ian ed jon hal],
'cath' => %w[fred bob ed gav hal col ian abe dan jon],
'dee' => %w[fred jon col abe ian hal gav dan bob ed],
'eve' => %w[jon hal fred dan abe gav col ed ian bob],
'fay' => %w[bob abe ed ian jon dan fred gav col hal],
'gay' => %w[jon gav hal fred bob abe col ed dan ian],
'hope' => %w[gav jon bob abe ian dan hal ed col fred],
'ivy' => %w[ian col hal gav fred bob abe ed jon dan],
'jan' => %w[ed hal gav abe bob jon col ian fred dan],
}
@men = Hash[
%w[abe bob col dan ed fred gav hal ian jon].collect do |name|
[name, Person.new(name)]
end
]
@women = Hash[
%w[abi bea cath dee eve fay gay hope ivy jan].collect do |name|
[name, Person.new(name)]
end
]
@men.each {|name, man| man.preferences = @women.values_at(*prefs[name])}
@women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])}
def match_couples(men, women)
men.each_value {|man| man.free}
women.each_value {|woman| woman.free}
while m = men.values.find {|man| man.single?} do
puts "considering single man
w = m.preferences.find {|woman| not m.proposals.include?(woman)}
m.propose_to(w)
end
end
match_couples @men, @women
@men.each_value.collect {|man| puts "
class Person
def more_preferable_people
( @preferences.partition {|p| better_choice?(p)} ).first
end
end
require 'set'
def stability(men)
unstable = Set.new
men.each_value do |man|
woman = man.fiance
puts "considering
man.more_preferable_people.each do |other_woman|
if other_woman.more_preferable_people.include?(man)
puts "an unstable pairing:
unstable << [man, other_woman]
end
end
woman.more_preferable_people.each do |other_man|
if other_man.more_preferable_people.include?(woman)
puts "an unstable pairing:
unstable << [other_man, woman]
end
end
end
if unstable.empty?
puts "these couples are stable"
else
puts "uh oh"
unstable.each do |a,b|
puts "
end
end
end
stability @men
puts "\nwhat if abe and bob swap..."
def swap(m1, m2)
w1 = m1.fiance
w2 = m2.fiance
m1.fiance = w2
w1.fiance = m2
m2.fiance = w1
w2.fiance = m1
end
swap *@men.values_at('abe','bob')
@men.each_value.collect {|man| puts "
stability @men
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Write a version of this Ruby function in C# with identical behavior. | class Person
def initialize(name)
@name = name
@fiance = nil
@preferences = []
@proposals = []
end
attr_reader :name, :proposals
attr_accessor :fiance, :preferences
def to_s
@name
end
def free
@fiance = nil
end
def single?
@fiance == nil
end
def engage(person)
self.fiance = person
person.fiance = self
end
def better_choice?(person)
@preferences.index(person) < @preferences.index(@fiance)
end
def propose_to(person)
puts "
@proposals << person
person.respond_to_proposal_from(self)
end
def respond_to_proposal_from(person)
if single?
puts "
engage(person)
elsif better_choice?(person)
puts "
@fiance.free
engage(person)
else
puts "
end
end
end
prefs = {
'abe' => %w[abi eve cath ivy jan dee fay bea hope gay],
'bob' => %w[cath hope abi dee eve fay bea jan ivy gay],
'col' => %w[hope eve abi dee bea fay ivy gay cath jan],
'dan' => %w[ivy fay dee gay hope eve jan bea cath abi],
'ed' => %w[jan dee bea cath fay eve abi ivy hope gay],
'fred' => %w[bea abi dee gay eve ivy cath jan hope fay],
'gav' => %w[gay eve ivy bea cath abi dee hope jan fay],
'hal' => %w[abi eve hope fay ivy cath jan bea gay dee],
'ian' => %w[hope cath dee gay bea abi fay ivy jan eve],
'jon' => %w[abi fay jan gay eve bea dee cath ivy hope],
'abi' => %w[bob fred jon gav ian abe dan ed col hal],
'bea' => %w[bob abe col fred gav dan ian ed jon hal],
'cath' => %w[fred bob ed gav hal col ian abe dan jon],
'dee' => %w[fred jon col abe ian hal gav dan bob ed],
'eve' => %w[jon hal fred dan abe gav col ed ian bob],
'fay' => %w[bob abe ed ian jon dan fred gav col hal],
'gay' => %w[jon gav hal fred bob abe col ed dan ian],
'hope' => %w[gav jon bob abe ian dan hal ed col fred],
'ivy' => %w[ian col hal gav fred bob abe ed jon dan],
'jan' => %w[ed hal gav abe bob jon col ian fred dan],
}
@men = Hash[
%w[abe bob col dan ed fred gav hal ian jon].collect do |name|
[name, Person.new(name)]
end
]
@women = Hash[
%w[abi bea cath dee eve fay gay hope ivy jan].collect do |name|
[name, Person.new(name)]
end
]
@men.each {|name, man| man.preferences = @women.values_at(*prefs[name])}
@women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])}
def match_couples(men, women)
men.each_value {|man| man.free}
women.each_value {|woman| woman.free}
while m = men.values.find {|man| man.single?} do
puts "considering single man
w = m.preferences.find {|woman| not m.proposals.include?(woman)}
m.propose_to(w)
end
end
match_couples @men, @women
@men.each_value.collect {|man| puts "
class Person
def more_preferable_people
( @preferences.partition {|p| better_choice?(p)} ).first
end
end
require 'set'
def stability(men)
unstable = Set.new
men.each_value do |man|
woman = man.fiance
puts "considering
man.more_preferable_people.each do |other_woman|
if other_woman.more_preferable_people.include?(man)
puts "an unstable pairing:
unstable << [man, other_woman]
end
end
woman.more_preferable_people.each do |other_man|
if other_man.more_preferable_people.include?(woman)
puts "an unstable pairing:
unstable << [other_man, woman]
end
end
end
if unstable.empty?
puts "these couples are stable"
else
puts "uh oh"
unstable.each do |a,b|
puts "
end
end
end
stability @men
puts "\nwhat if abe and bob swap..."
def swap(m1, m2)
w1 = m1.fiance
w2 = m2.fiance
m1.fiance = w2
w1.fiance = m2
m2.fiance = w1
w2.fiance = m1
end
swap *@men.values_at('abe','bob')
@men.each_value.collect {|man| puts "
stability @men
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Produce a language-to-language conversion: from Ruby to C++, same semantics. | class Person
def initialize(name)
@name = name
@fiance = nil
@preferences = []
@proposals = []
end
attr_reader :name, :proposals
attr_accessor :fiance, :preferences
def to_s
@name
end
def free
@fiance = nil
end
def single?
@fiance == nil
end
def engage(person)
self.fiance = person
person.fiance = self
end
def better_choice?(person)
@preferences.index(person) < @preferences.index(@fiance)
end
def propose_to(person)
puts "
@proposals << person
person.respond_to_proposal_from(self)
end
def respond_to_proposal_from(person)
if single?
puts "
engage(person)
elsif better_choice?(person)
puts "
@fiance.free
engage(person)
else
puts "
end
end
end
prefs = {
'abe' => %w[abi eve cath ivy jan dee fay bea hope gay],
'bob' => %w[cath hope abi dee eve fay bea jan ivy gay],
'col' => %w[hope eve abi dee bea fay ivy gay cath jan],
'dan' => %w[ivy fay dee gay hope eve jan bea cath abi],
'ed' => %w[jan dee bea cath fay eve abi ivy hope gay],
'fred' => %w[bea abi dee gay eve ivy cath jan hope fay],
'gav' => %w[gay eve ivy bea cath abi dee hope jan fay],
'hal' => %w[abi eve hope fay ivy cath jan bea gay dee],
'ian' => %w[hope cath dee gay bea abi fay ivy jan eve],
'jon' => %w[abi fay jan gay eve bea dee cath ivy hope],
'abi' => %w[bob fred jon gav ian abe dan ed col hal],
'bea' => %w[bob abe col fred gav dan ian ed jon hal],
'cath' => %w[fred bob ed gav hal col ian abe dan jon],
'dee' => %w[fred jon col abe ian hal gav dan bob ed],
'eve' => %w[jon hal fred dan abe gav col ed ian bob],
'fay' => %w[bob abe ed ian jon dan fred gav col hal],
'gay' => %w[jon gav hal fred bob abe col ed dan ian],
'hope' => %w[gav jon bob abe ian dan hal ed col fred],
'ivy' => %w[ian col hal gav fred bob abe ed jon dan],
'jan' => %w[ed hal gav abe bob jon col ian fred dan],
}
@men = Hash[
%w[abe bob col dan ed fred gav hal ian jon].collect do |name|
[name, Person.new(name)]
end
]
@women = Hash[
%w[abi bea cath dee eve fay gay hope ivy jan].collect do |name|
[name, Person.new(name)]
end
]
@men.each {|name, man| man.preferences = @women.values_at(*prefs[name])}
@women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])}
def match_couples(men, women)
men.each_value {|man| man.free}
women.each_value {|woman| woman.free}
while m = men.values.find {|man| man.single?} do
puts "considering single man
w = m.preferences.find {|woman| not m.proposals.include?(woman)}
m.propose_to(w)
end
end
match_couples @men, @women
@men.each_value.collect {|man| puts "
class Person
def more_preferable_people
( @preferences.partition {|p| better_choice?(p)} ).first
end
end
require 'set'
def stability(men)
unstable = Set.new
men.each_value do |man|
woman = man.fiance
puts "considering
man.more_preferable_people.each do |other_woman|
if other_woman.more_preferable_people.include?(man)
puts "an unstable pairing:
unstable << [man, other_woman]
end
end
woman.more_preferable_people.each do |other_man|
if other_man.more_preferable_people.include?(woman)
puts "an unstable pairing:
unstable << [other_man, woman]
end
end
end
if unstable.empty?
puts "these couples are stable"
else
puts "uh oh"
unstable.each do |a,b|
puts "
end
end
end
stability @men
puts "\nwhat if abe and bob swap..."
def swap(m1, m2)
w1 = m1.fiance
w2 = m2.fiance
m1.fiance = w2
w1.fiance = m2
m2.fiance = w1
w2.fiance = m1
end
swap *@men.values_at('abe','bob')
@men.each_value.collect {|man| puts "
stability @men
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Transform the following Ruby implementation into Python, maintaining the same output and logic. | class Person
def initialize(name)
@name = name
@fiance = nil
@preferences = []
@proposals = []
end
attr_reader :name, :proposals
attr_accessor :fiance, :preferences
def to_s
@name
end
def free
@fiance = nil
end
def single?
@fiance == nil
end
def engage(person)
self.fiance = person
person.fiance = self
end
def better_choice?(person)
@preferences.index(person) < @preferences.index(@fiance)
end
def propose_to(person)
puts "
@proposals << person
person.respond_to_proposal_from(self)
end
def respond_to_proposal_from(person)
if single?
puts "
engage(person)
elsif better_choice?(person)
puts "
@fiance.free
engage(person)
else
puts "
end
end
end
prefs = {
'abe' => %w[abi eve cath ivy jan dee fay bea hope gay],
'bob' => %w[cath hope abi dee eve fay bea jan ivy gay],
'col' => %w[hope eve abi dee bea fay ivy gay cath jan],
'dan' => %w[ivy fay dee gay hope eve jan bea cath abi],
'ed' => %w[jan dee bea cath fay eve abi ivy hope gay],
'fred' => %w[bea abi dee gay eve ivy cath jan hope fay],
'gav' => %w[gay eve ivy bea cath abi dee hope jan fay],
'hal' => %w[abi eve hope fay ivy cath jan bea gay dee],
'ian' => %w[hope cath dee gay bea abi fay ivy jan eve],
'jon' => %w[abi fay jan gay eve bea dee cath ivy hope],
'abi' => %w[bob fred jon gav ian abe dan ed col hal],
'bea' => %w[bob abe col fred gav dan ian ed jon hal],
'cath' => %w[fred bob ed gav hal col ian abe dan jon],
'dee' => %w[fred jon col abe ian hal gav dan bob ed],
'eve' => %w[jon hal fred dan abe gav col ed ian bob],
'fay' => %w[bob abe ed ian jon dan fred gav col hal],
'gay' => %w[jon gav hal fred bob abe col ed dan ian],
'hope' => %w[gav jon bob abe ian dan hal ed col fred],
'ivy' => %w[ian col hal gav fred bob abe ed jon dan],
'jan' => %w[ed hal gav abe bob jon col ian fred dan],
}
@men = Hash[
%w[abe bob col dan ed fred gav hal ian jon].collect do |name|
[name, Person.new(name)]
end
]
@women = Hash[
%w[abi bea cath dee eve fay gay hope ivy jan].collect do |name|
[name, Person.new(name)]
end
]
@men.each {|name, man| man.preferences = @women.values_at(*prefs[name])}
@women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])}
def match_couples(men, women)
men.each_value {|man| man.free}
women.each_value {|woman| woman.free}
while m = men.values.find {|man| man.single?} do
puts "considering single man
w = m.preferences.find {|woman| not m.proposals.include?(woman)}
m.propose_to(w)
end
end
match_couples @men, @women
@men.each_value.collect {|man| puts "
class Person
def more_preferable_people
( @preferences.partition {|p| better_choice?(p)} ).first
end
end
require 'set'
def stability(men)
unstable = Set.new
men.each_value do |man|
woman = man.fiance
puts "considering
man.more_preferable_people.each do |other_woman|
if other_woman.more_preferable_people.include?(man)
puts "an unstable pairing:
unstable << [man, other_woman]
end
end
woman.more_preferable_people.each do |other_man|
if other_man.more_preferable_people.include?(woman)
puts "an unstable pairing:
unstable << [other_man, woman]
end
end
end
if unstable.empty?
puts "these couples are stable"
else
puts "uh oh"
unstable.each do |a,b|
puts "
end
end
end
stability @men
puts "\nwhat if abe and bob swap..."
def swap(m1, m2)
w1 = m1.fiance
w2 = m2.fiance
m1.fiance = w2
w1.fiance = m2
m2.fiance = w1
w2.fiance = m1
end
swap *@men.values_at('abe','bob')
@men.each_value.collect {|man| puts "
stability @men
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Translate this program into VB but keep the logic exactly as in Ruby. | class Person
def initialize(name)
@name = name
@fiance = nil
@preferences = []
@proposals = []
end
attr_reader :name, :proposals
attr_accessor :fiance, :preferences
def to_s
@name
end
def free
@fiance = nil
end
def single?
@fiance == nil
end
def engage(person)
self.fiance = person
person.fiance = self
end
def better_choice?(person)
@preferences.index(person) < @preferences.index(@fiance)
end
def propose_to(person)
puts "
@proposals << person
person.respond_to_proposal_from(self)
end
def respond_to_proposal_from(person)
if single?
puts "
engage(person)
elsif better_choice?(person)
puts "
@fiance.free
engage(person)
else
puts "
end
end
end
prefs = {
'abe' => %w[abi eve cath ivy jan dee fay bea hope gay],
'bob' => %w[cath hope abi dee eve fay bea jan ivy gay],
'col' => %w[hope eve abi dee bea fay ivy gay cath jan],
'dan' => %w[ivy fay dee gay hope eve jan bea cath abi],
'ed' => %w[jan dee bea cath fay eve abi ivy hope gay],
'fred' => %w[bea abi dee gay eve ivy cath jan hope fay],
'gav' => %w[gay eve ivy bea cath abi dee hope jan fay],
'hal' => %w[abi eve hope fay ivy cath jan bea gay dee],
'ian' => %w[hope cath dee gay bea abi fay ivy jan eve],
'jon' => %w[abi fay jan gay eve bea dee cath ivy hope],
'abi' => %w[bob fred jon gav ian abe dan ed col hal],
'bea' => %w[bob abe col fred gav dan ian ed jon hal],
'cath' => %w[fred bob ed gav hal col ian abe dan jon],
'dee' => %w[fred jon col abe ian hal gav dan bob ed],
'eve' => %w[jon hal fred dan abe gav col ed ian bob],
'fay' => %w[bob abe ed ian jon dan fred gav col hal],
'gay' => %w[jon gav hal fred bob abe col ed dan ian],
'hope' => %w[gav jon bob abe ian dan hal ed col fred],
'ivy' => %w[ian col hal gav fred bob abe ed jon dan],
'jan' => %w[ed hal gav abe bob jon col ian fred dan],
}
@men = Hash[
%w[abe bob col dan ed fred gav hal ian jon].collect do |name|
[name, Person.new(name)]
end
]
@women = Hash[
%w[abi bea cath dee eve fay gay hope ivy jan].collect do |name|
[name, Person.new(name)]
end
]
@men.each {|name, man| man.preferences = @women.values_at(*prefs[name])}
@women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])}
def match_couples(men, women)
men.each_value {|man| man.free}
women.each_value {|woman| woman.free}
while m = men.values.find {|man| man.single?} do
puts "considering single man
w = m.preferences.find {|woman| not m.proposals.include?(woman)}
m.propose_to(w)
end
end
match_couples @men, @women
@men.each_value.collect {|man| puts "
class Person
def more_preferable_people
( @preferences.partition {|p| better_choice?(p)} ).first
end
end
require 'set'
def stability(men)
unstable = Set.new
men.each_value do |man|
woman = man.fiance
puts "considering
man.more_preferable_people.each do |other_woman|
if other_woman.more_preferable_people.include?(man)
puts "an unstable pairing:
unstable << [man, other_woman]
end
end
woman.more_preferable_people.each do |other_man|
if other_man.more_preferable_people.include?(woman)
puts "an unstable pairing:
unstable << [other_man, woman]
end
end
end
if unstable.empty?
puts "these couples are stable"
else
puts "uh oh"
unstable.each do |a,b|
puts "
end
end
end
stability @men
puts "\nwhat if abe and bob swap..."
def swap(m1, m2)
w1 = m1.fiance
w2 = m2.fiance
m1.fiance = w2
w1.fiance = m2
m2.fiance = w1
w2.fiance = m1
end
swap *@men.values_at('abe','bob')
@men.each_value.collect {|man| puts "
stability @men
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Produce a functionally identical Go code for the snippet given in Ruby. | class Person
def initialize(name)
@name = name
@fiance = nil
@preferences = []
@proposals = []
end
attr_reader :name, :proposals
attr_accessor :fiance, :preferences
def to_s
@name
end
def free
@fiance = nil
end
def single?
@fiance == nil
end
def engage(person)
self.fiance = person
person.fiance = self
end
def better_choice?(person)
@preferences.index(person) < @preferences.index(@fiance)
end
def propose_to(person)
puts "
@proposals << person
person.respond_to_proposal_from(self)
end
def respond_to_proposal_from(person)
if single?
puts "
engage(person)
elsif better_choice?(person)
puts "
@fiance.free
engage(person)
else
puts "
end
end
end
prefs = {
'abe' => %w[abi eve cath ivy jan dee fay bea hope gay],
'bob' => %w[cath hope abi dee eve fay bea jan ivy gay],
'col' => %w[hope eve abi dee bea fay ivy gay cath jan],
'dan' => %w[ivy fay dee gay hope eve jan bea cath abi],
'ed' => %w[jan dee bea cath fay eve abi ivy hope gay],
'fred' => %w[bea abi dee gay eve ivy cath jan hope fay],
'gav' => %w[gay eve ivy bea cath abi dee hope jan fay],
'hal' => %w[abi eve hope fay ivy cath jan bea gay dee],
'ian' => %w[hope cath dee gay bea abi fay ivy jan eve],
'jon' => %w[abi fay jan gay eve bea dee cath ivy hope],
'abi' => %w[bob fred jon gav ian abe dan ed col hal],
'bea' => %w[bob abe col fred gav dan ian ed jon hal],
'cath' => %w[fred bob ed gav hal col ian abe dan jon],
'dee' => %w[fred jon col abe ian hal gav dan bob ed],
'eve' => %w[jon hal fred dan abe gav col ed ian bob],
'fay' => %w[bob abe ed ian jon dan fred gav col hal],
'gay' => %w[jon gav hal fred bob abe col ed dan ian],
'hope' => %w[gav jon bob abe ian dan hal ed col fred],
'ivy' => %w[ian col hal gav fred bob abe ed jon dan],
'jan' => %w[ed hal gav abe bob jon col ian fred dan],
}
@men = Hash[
%w[abe bob col dan ed fred gav hal ian jon].collect do |name|
[name, Person.new(name)]
end
]
@women = Hash[
%w[abi bea cath dee eve fay gay hope ivy jan].collect do |name|
[name, Person.new(name)]
end
]
@men.each {|name, man| man.preferences = @women.values_at(*prefs[name])}
@women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])}
def match_couples(men, women)
men.each_value {|man| man.free}
women.each_value {|woman| woman.free}
while m = men.values.find {|man| man.single?} do
puts "considering single man
w = m.preferences.find {|woman| not m.proposals.include?(woman)}
m.propose_to(w)
end
end
match_couples @men, @women
@men.each_value.collect {|man| puts "
class Person
def more_preferable_people
( @preferences.partition {|p| better_choice?(p)} ).first
end
end
require 'set'
def stability(men)
unstable = Set.new
men.each_value do |man|
woman = man.fiance
puts "considering
man.more_preferable_people.each do |other_woman|
if other_woman.more_preferable_people.include?(man)
puts "an unstable pairing:
unstable << [man, other_woman]
end
end
woman.more_preferable_people.each do |other_man|
if other_man.more_preferable_people.include?(woman)
puts "an unstable pairing:
unstable << [other_man, woman]
end
end
end
if unstable.empty?
puts "these couples are stable"
else
puts "uh oh"
unstable.each do |a,b|
puts "
end
end
end
stability @men
puts "\nwhat if abe and bob swap..."
def swap(m1, m2)
w1 = m1.fiance
w2 = m2.fiance
m1.fiance = w2
w1.fiance = m2
m2.fiance = w1
w2.fiance = m1
end
swap *@men.values_at('abe','bob')
@men.each_value.collect {|man| puts "
stability @men
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Write a version of this Scala function in C with identical behavior. | object SMP extends App {
private def checkMarriages(): Unit =
if (check)
println("Marriages are stable")
else
println("Marriages are unstable")
private def swap() {
val girl1 = girls.head
val girl2 = girls(1)
val tmp = girl2 -> matches(girl1)
matches += girl1 -> matches(girl2)
matches += tmp
println(girl1 + " and " + girl2 + " have switched partners")
}
private type TM = scala.collection.mutable.TreeMap[String, String]
private def check: Boolean = {
if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet))
return false
val invertedMatches = new TM
matches foreach { invertedMatches += _.swap }
for ((k, v) <- matches) {
val shePrefers = girlPrefers(k)
val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v))
val hePrefers = guyPrefers(v)
val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k))
for (guy <- sheLikesBetter) {
val fiance = invertedMatches(guy)
val guy_p = guyPrefers(guy)
if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) {
println(s"$k likes $guy better than $v and $guy likes $k better than their current partner")
return false
}
}
for (girl <- heLikesBetter) {
val fiance = matches(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) {
println(s"$v likes $girl better than $k and $girl likes $v better than their current partner")
return false
}
}
}
true
}
private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil
private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil
private val guyPrefers = Map("abe" -> List("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"),
"bob" -> List("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"),
"col" -> List("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"),
"dan" -> List("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"),
"ed" -> List("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"),
"fred" -> List("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"),
"gav" -> List("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"),
"hal" -> List("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"),
"ian" -> List("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"),
"jon" -> List("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"))
private val girlPrefers = Map("abi" -> List("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"),
"bea" -> List("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"),
"cath" -> List("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"),
"dee" -> List("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"),
"eve" -> List("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"),
"fay" -> List("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"),
"gay" -> List("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"),
"hope" -> List("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"),
"ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"),
"jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"))
private lazy val matches = {
val engagements = new TM
val freeGuys = scala.collection.mutable.Queue.empty ++ guys
while (freeGuys.nonEmpty) {
val guy = freeGuys.dequeue()
val guy_p = guyPrefers(guy)
var break = false
for (girl <- guy_p)
if (!break)
if (!engagements.contains(girl)) {
engagements(girl) = guy
break = true
}
else {
val other_guy = engagements(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) {
engagements(girl) = guy
freeGuys += other_guy
break = true
}
}
}
engagements foreach { e => println(s"${e._1} is engaged to ${e._2}") }
engagements
}
checkMarriages()
swap()
checkMarriages()
}
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Convert this Scala block to C#, preserving its control flow and logic. | object SMP extends App {
private def checkMarriages(): Unit =
if (check)
println("Marriages are stable")
else
println("Marriages are unstable")
private def swap() {
val girl1 = girls.head
val girl2 = girls(1)
val tmp = girl2 -> matches(girl1)
matches += girl1 -> matches(girl2)
matches += tmp
println(girl1 + " and " + girl2 + " have switched partners")
}
private type TM = scala.collection.mutable.TreeMap[String, String]
private def check: Boolean = {
if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet))
return false
val invertedMatches = new TM
matches foreach { invertedMatches += _.swap }
for ((k, v) <- matches) {
val shePrefers = girlPrefers(k)
val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v))
val hePrefers = guyPrefers(v)
val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k))
for (guy <- sheLikesBetter) {
val fiance = invertedMatches(guy)
val guy_p = guyPrefers(guy)
if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) {
println(s"$k likes $guy better than $v and $guy likes $k better than their current partner")
return false
}
}
for (girl <- heLikesBetter) {
val fiance = matches(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) {
println(s"$v likes $girl better than $k and $girl likes $v better than their current partner")
return false
}
}
}
true
}
private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil
private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil
private val guyPrefers = Map("abe" -> List("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"),
"bob" -> List("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"),
"col" -> List("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"),
"dan" -> List("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"),
"ed" -> List("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"),
"fred" -> List("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"),
"gav" -> List("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"),
"hal" -> List("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"),
"ian" -> List("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"),
"jon" -> List("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"))
private val girlPrefers = Map("abi" -> List("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"),
"bea" -> List("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"),
"cath" -> List("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"),
"dee" -> List("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"),
"eve" -> List("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"),
"fay" -> List("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"),
"gay" -> List("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"),
"hope" -> List("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"),
"ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"),
"jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"))
private lazy val matches = {
val engagements = new TM
val freeGuys = scala.collection.mutable.Queue.empty ++ guys
while (freeGuys.nonEmpty) {
val guy = freeGuys.dequeue()
val guy_p = guyPrefers(guy)
var break = false
for (girl <- guy_p)
if (!break)
if (!engagements.contains(girl)) {
engagements(girl) = guy
break = true
}
else {
val other_guy = engagements(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) {
engagements(girl) = guy
freeGuys += other_guy
break = true
}
}
}
engagements foreach { e => println(s"${e._1} is engaged to ${e._2}") }
engagements
}
checkMarriages()
swap()
checkMarriages()
}
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Convert the following code from Scala to C++, ensuring the logic remains intact. | object SMP extends App {
private def checkMarriages(): Unit =
if (check)
println("Marriages are stable")
else
println("Marriages are unstable")
private def swap() {
val girl1 = girls.head
val girl2 = girls(1)
val tmp = girl2 -> matches(girl1)
matches += girl1 -> matches(girl2)
matches += tmp
println(girl1 + " and " + girl2 + " have switched partners")
}
private type TM = scala.collection.mutable.TreeMap[String, String]
private def check: Boolean = {
if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet))
return false
val invertedMatches = new TM
matches foreach { invertedMatches += _.swap }
for ((k, v) <- matches) {
val shePrefers = girlPrefers(k)
val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v))
val hePrefers = guyPrefers(v)
val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k))
for (guy <- sheLikesBetter) {
val fiance = invertedMatches(guy)
val guy_p = guyPrefers(guy)
if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) {
println(s"$k likes $guy better than $v and $guy likes $k better than their current partner")
return false
}
}
for (girl <- heLikesBetter) {
val fiance = matches(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) {
println(s"$v likes $girl better than $k and $girl likes $v better than their current partner")
return false
}
}
}
true
}
private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil
private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil
private val guyPrefers = Map("abe" -> List("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"),
"bob" -> List("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"),
"col" -> List("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"),
"dan" -> List("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"),
"ed" -> List("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"),
"fred" -> List("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"),
"gav" -> List("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"),
"hal" -> List("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"),
"ian" -> List("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"),
"jon" -> List("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"))
private val girlPrefers = Map("abi" -> List("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"),
"bea" -> List("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"),
"cath" -> List("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"),
"dee" -> List("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"),
"eve" -> List("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"),
"fay" -> List("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"),
"gay" -> List("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"),
"hope" -> List("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"),
"ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"),
"jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"))
private lazy val matches = {
val engagements = new TM
val freeGuys = scala.collection.mutable.Queue.empty ++ guys
while (freeGuys.nonEmpty) {
val guy = freeGuys.dequeue()
val guy_p = guyPrefers(guy)
var break = false
for (girl <- guy_p)
if (!break)
if (!engagements.contains(girl)) {
engagements(girl) = guy
break = true
}
else {
val other_guy = engagements(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) {
engagements(girl) = guy
freeGuys += other_guy
break = true
}
}
}
engagements foreach { e => println(s"${e._1} is engaged to ${e._2}") }
engagements
}
checkMarriages()
swap()
checkMarriages()
}
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Port the provided Scala code into Python while preserving the original functionality. | object SMP extends App {
private def checkMarriages(): Unit =
if (check)
println("Marriages are stable")
else
println("Marriages are unstable")
private def swap() {
val girl1 = girls.head
val girl2 = girls(1)
val tmp = girl2 -> matches(girl1)
matches += girl1 -> matches(girl2)
matches += tmp
println(girl1 + " and " + girl2 + " have switched partners")
}
private type TM = scala.collection.mutable.TreeMap[String, String]
private def check: Boolean = {
if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet))
return false
val invertedMatches = new TM
matches foreach { invertedMatches += _.swap }
for ((k, v) <- matches) {
val shePrefers = girlPrefers(k)
val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v))
val hePrefers = guyPrefers(v)
val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k))
for (guy <- sheLikesBetter) {
val fiance = invertedMatches(guy)
val guy_p = guyPrefers(guy)
if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) {
println(s"$k likes $guy better than $v and $guy likes $k better than their current partner")
return false
}
}
for (girl <- heLikesBetter) {
val fiance = matches(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) {
println(s"$v likes $girl better than $k and $girl likes $v better than their current partner")
return false
}
}
}
true
}
private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil
private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil
private val guyPrefers = Map("abe" -> List("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"),
"bob" -> List("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"),
"col" -> List("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"),
"dan" -> List("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"),
"ed" -> List("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"),
"fred" -> List("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"),
"gav" -> List("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"),
"hal" -> List("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"),
"ian" -> List("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"),
"jon" -> List("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"))
private val girlPrefers = Map("abi" -> List("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"),
"bea" -> List("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"),
"cath" -> List("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"),
"dee" -> List("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"),
"eve" -> List("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"),
"fay" -> List("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"),
"gay" -> List("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"),
"hope" -> List("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"),
"ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"),
"jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"))
private lazy val matches = {
val engagements = new TM
val freeGuys = scala.collection.mutable.Queue.empty ++ guys
while (freeGuys.nonEmpty) {
val guy = freeGuys.dequeue()
val guy_p = guyPrefers(guy)
var break = false
for (girl <- guy_p)
if (!break)
if (!engagements.contains(girl)) {
engagements(girl) = guy
break = true
}
else {
val other_guy = engagements(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) {
engagements(girl) = guy
freeGuys += other_guy
break = true
}
}
}
engagements foreach { e => println(s"${e._1} is engaged to ${e._2}") }
engagements
}
checkMarriages()
swap()
checkMarriages()
}
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Change the programming language of this snippet from Scala to VB without modifying what it does. | object SMP extends App {
private def checkMarriages(): Unit =
if (check)
println("Marriages are stable")
else
println("Marriages are unstable")
private def swap() {
val girl1 = girls.head
val girl2 = girls(1)
val tmp = girl2 -> matches(girl1)
matches += girl1 -> matches(girl2)
matches += tmp
println(girl1 + " and " + girl2 + " have switched partners")
}
private type TM = scala.collection.mutable.TreeMap[String, String]
private def check: Boolean = {
if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet))
return false
val invertedMatches = new TM
matches foreach { invertedMatches += _.swap }
for ((k, v) <- matches) {
val shePrefers = girlPrefers(k)
val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v))
val hePrefers = guyPrefers(v)
val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k))
for (guy <- sheLikesBetter) {
val fiance = invertedMatches(guy)
val guy_p = guyPrefers(guy)
if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) {
println(s"$k likes $guy better than $v and $guy likes $k better than their current partner")
return false
}
}
for (girl <- heLikesBetter) {
val fiance = matches(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) {
println(s"$v likes $girl better than $k and $girl likes $v better than their current partner")
return false
}
}
}
true
}
private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil
private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil
private val guyPrefers = Map("abe" -> List("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"),
"bob" -> List("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"),
"col" -> List("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"),
"dan" -> List("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"),
"ed" -> List("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"),
"fred" -> List("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"),
"gav" -> List("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"),
"hal" -> List("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"),
"ian" -> List("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"),
"jon" -> List("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"))
private val girlPrefers = Map("abi" -> List("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"),
"bea" -> List("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"),
"cath" -> List("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"),
"dee" -> List("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"),
"eve" -> List("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"),
"fay" -> List("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"),
"gay" -> List("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"),
"hope" -> List("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"),
"ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"),
"jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"))
private lazy val matches = {
val engagements = new TM
val freeGuys = scala.collection.mutable.Queue.empty ++ guys
while (freeGuys.nonEmpty) {
val guy = freeGuys.dequeue()
val guy_p = guyPrefers(guy)
var break = false
for (girl <- guy_p)
if (!break)
if (!engagements.contains(girl)) {
engagements(girl) = guy
break = true
}
else {
val other_guy = engagements(girl)
val girl_p = girlPrefers(girl)
if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) {
engagements(girl) = guy
freeGuys += other_guy
break = true
}
}
}
engagements foreach { e => println(s"${e._1} is engaged to ${e._2}") }
engagements
}
checkMarriages()
swap()
checkMarriages()
}
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Translate this program into C but keep the logic exactly as in Swift. | class Person {
let name:String
var candidateIndex = 0
var fiance:Person?
var candidates = [Person]()
init(name:String) {
self.name = name
}
func rank(p:Person) -> Int {
for (i, candidate) in enumerate(self.candidates) {
if candidate === p {
return i
}
}
return self.candidates.count + 1
}
func prefers(p:Person) -> Bool {
if let fiance = self.fiance {
return self.rank(p) < self.rank(fiance)
}
return false
}
func nextCandidate() -> Person? {
if self.candidateIndex >= self.candidates.count {
return nil
}
return self.candidates[candidateIndex++]
}
func engageTo(p:Person) {
p.fiance?.fiance = nil
p.fiance = self
self.fiance?.fiance = nil
self.fiance = p
}
func swapWith(p:Person) {
let thisFiance = self.fiance
let pFiance = p.fiance
println("\(self.name) swapped partners with \(p.name)")
if pFiance != nil && thisFiance != nil {
self.engageTo(pFiance!)
p.engageTo(thisFiance!)
}
}
}
func isStable(guys:[Person], gals:[Person]) -> Bool {
for guy in guys {
for gal in gals {
if guy.prefers(gal) && gal.prefers(guy) {
return false
}
}
}
return true
}
func engageEveryone(guys:[Person]) {
var done = false
while !done {
done = true
for guy in guys {
if guy.fiance == nil {
done = false
if let gal = guy.nextCandidate() {
if gal.fiance == nil || gal.prefers(guy) {
guy.engageTo(gal)
}
}
}
}
}
}
func doMarriage() {
let abe = Person(name: "Abe")
let bob = Person(name: "Bob")
let col = Person(name: "Col")
let dan = Person(name: "Dan")
let ed = Person(name: "Ed")
let fred = Person(name: "Fred")
let gav = Person(name: "Gav")
let hal = Person(name: "Hal")
let ian = Person(name: "Ian")
let jon = Person(name: "Jon")
let abi = Person(name: "Abi")
let bea = Person(name: "Bea")
let cath = Person(name: "Cath")
let dee = Person(name: "Dee")
let eve = Person(name: "Eve")
let fay = Person(name: "Fay")
let gay = Person(name: "Gay")
let hope = Person(name: "Hope")
let ivy = Person(name: "Ivy")
let jan = Person(name: "Jan")
abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]
bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]
col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]
dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]
ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]
fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]
gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]
hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]
ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]
jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]
abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]
bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]
cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]
dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]
eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]
fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]
gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]
hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]
ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]
jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]
let guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]
let gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]
engageEveryone(guys)
for guy in guys {
println("\(guy.name) is engaged to \(guy.fiance!.name)")
}
println("Stable = \(isStable(guys, gals))")
jon.swapWith(fred)
println("Stable = \(isStable(guys, gals))")
}
doMarriage()
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Swift version. | class Person {
let name:String
var candidateIndex = 0
var fiance:Person?
var candidates = [Person]()
init(name:String) {
self.name = name
}
func rank(p:Person) -> Int {
for (i, candidate) in enumerate(self.candidates) {
if candidate === p {
return i
}
}
return self.candidates.count + 1
}
func prefers(p:Person) -> Bool {
if let fiance = self.fiance {
return self.rank(p) < self.rank(fiance)
}
return false
}
func nextCandidate() -> Person? {
if self.candidateIndex >= self.candidates.count {
return nil
}
return self.candidates[candidateIndex++]
}
func engageTo(p:Person) {
p.fiance?.fiance = nil
p.fiance = self
self.fiance?.fiance = nil
self.fiance = p
}
func swapWith(p:Person) {
let thisFiance = self.fiance
let pFiance = p.fiance
println("\(self.name) swapped partners with \(p.name)")
if pFiance != nil && thisFiance != nil {
self.engageTo(pFiance!)
p.engageTo(thisFiance!)
}
}
}
func isStable(guys:[Person], gals:[Person]) -> Bool {
for guy in guys {
for gal in gals {
if guy.prefers(gal) && gal.prefers(guy) {
return false
}
}
}
return true
}
func engageEveryone(guys:[Person]) {
var done = false
while !done {
done = true
for guy in guys {
if guy.fiance == nil {
done = false
if let gal = guy.nextCandidate() {
if gal.fiance == nil || gal.prefers(guy) {
guy.engageTo(gal)
}
}
}
}
}
}
func doMarriage() {
let abe = Person(name: "Abe")
let bob = Person(name: "Bob")
let col = Person(name: "Col")
let dan = Person(name: "Dan")
let ed = Person(name: "Ed")
let fred = Person(name: "Fred")
let gav = Person(name: "Gav")
let hal = Person(name: "Hal")
let ian = Person(name: "Ian")
let jon = Person(name: "Jon")
let abi = Person(name: "Abi")
let bea = Person(name: "Bea")
let cath = Person(name: "Cath")
let dee = Person(name: "Dee")
let eve = Person(name: "Eve")
let fay = Person(name: "Fay")
let gay = Person(name: "Gay")
let hope = Person(name: "Hope")
let ivy = Person(name: "Ivy")
let jan = Person(name: "Jan")
abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]
bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]
col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]
dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]
ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]
fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]
gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]
hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]
ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]
jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]
abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]
bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]
cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]
dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]
eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]
fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]
gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]
hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]
ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]
jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]
let guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]
let gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]
engageEveryone(guys)
for guy in guys {
println("\(guy.name) is engaged to \(guy.fiance!.name)")
}
println("Stable = \(isStable(guys, gals))")
jon.swapWith(fred)
println("Stable = \(isStable(guys, gals))")
}
doMarriage()
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Change the programming language of this snippet from Swift to C++ without modifying what it does. | class Person {
let name:String
var candidateIndex = 0
var fiance:Person?
var candidates = [Person]()
init(name:String) {
self.name = name
}
func rank(p:Person) -> Int {
for (i, candidate) in enumerate(self.candidates) {
if candidate === p {
return i
}
}
return self.candidates.count + 1
}
func prefers(p:Person) -> Bool {
if let fiance = self.fiance {
return self.rank(p) < self.rank(fiance)
}
return false
}
func nextCandidate() -> Person? {
if self.candidateIndex >= self.candidates.count {
return nil
}
return self.candidates[candidateIndex++]
}
func engageTo(p:Person) {
p.fiance?.fiance = nil
p.fiance = self
self.fiance?.fiance = nil
self.fiance = p
}
func swapWith(p:Person) {
let thisFiance = self.fiance
let pFiance = p.fiance
println("\(self.name) swapped partners with \(p.name)")
if pFiance != nil && thisFiance != nil {
self.engageTo(pFiance!)
p.engageTo(thisFiance!)
}
}
}
func isStable(guys:[Person], gals:[Person]) -> Bool {
for guy in guys {
for gal in gals {
if guy.prefers(gal) && gal.prefers(guy) {
return false
}
}
}
return true
}
func engageEveryone(guys:[Person]) {
var done = false
while !done {
done = true
for guy in guys {
if guy.fiance == nil {
done = false
if let gal = guy.nextCandidate() {
if gal.fiance == nil || gal.prefers(guy) {
guy.engageTo(gal)
}
}
}
}
}
}
func doMarriage() {
let abe = Person(name: "Abe")
let bob = Person(name: "Bob")
let col = Person(name: "Col")
let dan = Person(name: "Dan")
let ed = Person(name: "Ed")
let fred = Person(name: "Fred")
let gav = Person(name: "Gav")
let hal = Person(name: "Hal")
let ian = Person(name: "Ian")
let jon = Person(name: "Jon")
let abi = Person(name: "Abi")
let bea = Person(name: "Bea")
let cath = Person(name: "Cath")
let dee = Person(name: "Dee")
let eve = Person(name: "Eve")
let fay = Person(name: "Fay")
let gay = Person(name: "Gay")
let hope = Person(name: "Hope")
let ivy = Person(name: "Ivy")
let jan = Person(name: "Jan")
abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]
bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]
col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]
dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]
ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]
fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]
gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]
hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]
ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]
jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]
abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]
bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]
cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]
dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]
eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]
fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]
gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]
hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]
ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]
jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]
let guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]
let gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]
engageEveryone(guys)
for guy in guys {
println("\(guy.name) is engaged to \(guy.fiance!.name)")
}
println("Stable = \(isStable(guys, gals))")
jon.swapWith(fred)
println("Stable = \(isStable(guys, gals))")
}
doMarriage()
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Swift version. | class Person {
let name:String
var candidateIndex = 0
var fiance:Person?
var candidates = [Person]()
init(name:String) {
self.name = name
}
func rank(p:Person) -> Int {
for (i, candidate) in enumerate(self.candidates) {
if candidate === p {
return i
}
}
return self.candidates.count + 1
}
func prefers(p:Person) -> Bool {
if let fiance = self.fiance {
return self.rank(p) < self.rank(fiance)
}
return false
}
func nextCandidate() -> Person? {
if self.candidateIndex >= self.candidates.count {
return nil
}
return self.candidates[candidateIndex++]
}
func engageTo(p:Person) {
p.fiance?.fiance = nil
p.fiance = self
self.fiance?.fiance = nil
self.fiance = p
}
func swapWith(p:Person) {
let thisFiance = self.fiance
let pFiance = p.fiance
println("\(self.name) swapped partners with \(p.name)")
if pFiance != nil && thisFiance != nil {
self.engageTo(pFiance!)
p.engageTo(thisFiance!)
}
}
}
func isStable(guys:[Person], gals:[Person]) -> Bool {
for guy in guys {
for gal in gals {
if guy.prefers(gal) && gal.prefers(guy) {
return false
}
}
}
return true
}
func engageEveryone(guys:[Person]) {
var done = false
while !done {
done = true
for guy in guys {
if guy.fiance == nil {
done = false
if let gal = guy.nextCandidate() {
if gal.fiance == nil || gal.prefers(guy) {
guy.engageTo(gal)
}
}
}
}
}
}
func doMarriage() {
let abe = Person(name: "Abe")
let bob = Person(name: "Bob")
let col = Person(name: "Col")
let dan = Person(name: "Dan")
let ed = Person(name: "Ed")
let fred = Person(name: "Fred")
let gav = Person(name: "Gav")
let hal = Person(name: "Hal")
let ian = Person(name: "Ian")
let jon = Person(name: "Jon")
let abi = Person(name: "Abi")
let bea = Person(name: "Bea")
let cath = Person(name: "Cath")
let dee = Person(name: "Dee")
let eve = Person(name: "Eve")
let fay = Person(name: "Fay")
let gay = Person(name: "Gay")
let hope = Person(name: "Hope")
let ivy = Person(name: "Ivy")
let jan = Person(name: "Jan")
abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]
bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]
col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]
dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]
ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]
fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]
gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]
hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]
ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]
jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]
abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]
bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]
cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]
dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]
eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]
fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]
gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]
hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]
ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]
jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]
let guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]
let gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]
engageEveryone(guys)
for guy in guys {
println("\(guy.name) is engaged to \(guy.fiance!.name)")
}
println("Stable = \(isStable(guys, gals))")
jon.swapWith(fred)
println("Stable = \(isStable(guys, gals))")
}
doMarriage()
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Rewrite the snippet below in VB so it works the same as the original Swift code. | class Person {
let name:String
var candidateIndex = 0
var fiance:Person?
var candidates = [Person]()
init(name:String) {
self.name = name
}
func rank(p:Person) -> Int {
for (i, candidate) in enumerate(self.candidates) {
if candidate === p {
return i
}
}
return self.candidates.count + 1
}
func prefers(p:Person) -> Bool {
if let fiance = self.fiance {
return self.rank(p) < self.rank(fiance)
}
return false
}
func nextCandidate() -> Person? {
if self.candidateIndex >= self.candidates.count {
return nil
}
return self.candidates[candidateIndex++]
}
func engageTo(p:Person) {
p.fiance?.fiance = nil
p.fiance = self
self.fiance?.fiance = nil
self.fiance = p
}
func swapWith(p:Person) {
let thisFiance = self.fiance
let pFiance = p.fiance
println("\(self.name) swapped partners with \(p.name)")
if pFiance != nil && thisFiance != nil {
self.engageTo(pFiance!)
p.engageTo(thisFiance!)
}
}
}
func isStable(guys:[Person], gals:[Person]) -> Bool {
for guy in guys {
for gal in gals {
if guy.prefers(gal) && gal.prefers(guy) {
return false
}
}
}
return true
}
func engageEveryone(guys:[Person]) {
var done = false
while !done {
done = true
for guy in guys {
if guy.fiance == nil {
done = false
if let gal = guy.nextCandidate() {
if gal.fiance == nil || gal.prefers(guy) {
guy.engageTo(gal)
}
}
}
}
}
}
func doMarriage() {
let abe = Person(name: "Abe")
let bob = Person(name: "Bob")
let col = Person(name: "Col")
let dan = Person(name: "Dan")
let ed = Person(name: "Ed")
let fred = Person(name: "Fred")
let gav = Person(name: "Gav")
let hal = Person(name: "Hal")
let ian = Person(name: "Ian")
let jon = Person(name: "Jon")
let abi = Person(name: "Abi")
let bea = Person(name: "Bea")
let cath = Person(name: "Cath")
let dee = Person(name: "Dee")
let eve = Person(name: "Eve")
let fay = Person(name: "Fay")
let gay = Person(name: "Gay")
let hope = Person(name: "Hope")
let ivy = Person(name: "Ivy")
let jan = Person(name: "Jan")
abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]
bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]
col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]
dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]
ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]
fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]
gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]
hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]
ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]
jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]
abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]
bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]
cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]
dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]
eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]
fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]
gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]
hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]
ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]
jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]
let guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]
let gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]
engageEveryone(guys)
for guy in guys {
println("\(guy.name) is engaged to \(guy.fiance!.name)")
}
println("Stable = \(isStable(guys, gals))")
jon.swapWith(fred)
println("Stable = \(isStable(guys, gals))")
}
doMarriage()
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Write the same code in Go as shown below in Swift. | class Person {
let name:String
var candidateIndex = 0
var fiance:Person?
var candidates = [Person]()
init(name:String) {
self.name = name
}
func rank(p:Person) -> Int {
for (i, candidate) in enumerate(self.candidates) {
if candidate === p {
return i
}
}
return self.candidates.count + 1
}
func prefers(p:Person) -> Bool {
if let fiance = self.fiance {
return self.rank(p) < self.rank(fiance)
}
return false
}
func nextCandidate() -> Person? {
if self.candidateIndex >= self.candidates.count {
return nil
}
return self.candidates[candidateIndex++]
}
func engageTo(p:Person) {
p.fiance?.fiance = nil
p.fiance = self
self.fiance?.fiance = nil
self.fiance = p
}
func swapWith(p:Person) {
let thisFiance = self.fiance
let pFiance = p.fiance
println("\(self.name) swapped partners with \(p.name)")
if pFiance != nil && thisFiance != nil {
self.engageTo(pFiance!)
p.engageTo(thisFiance!)
}
}
}
func isStable(guys:[Person], gals:[Person]) -> Bool {
for guy in guys {
for gal in gals {
if guy.prefers(gal) && gal.prefers(guy) {
return false
}
}
}
return true
}
func engageEveryone(guys:[Person]) {
var done = false
while !done {
done = true
for guy in guys {
if guy.fiance == nil {
done = false
if let gal = guy.nextCandidate() {
if gal.fiance == nil || gal.prefers(guy) {
guy.engageTo(gal)
}
}
}
}
}
}
func doMarriage() {
let abe = Person(name: "Abe")
let bob = Person(name: "Bob")
let col = Person(name: "Col")
let dan = Person(name: "Dan")
let ed = Person(name: "Ed")
let fred = Person(name: "Fred")
let gav = Person(name: "Gav")
let hal = Person(name: "Hal")
let ian = Person(name: "Ian")
let jon = Person(name: "Jon")
let abi = Person(name: "Abi")
let bea = Person(name: "Bea")
let cath = Person(name: "Cath")
let dee = Person(name: "Dee")
let eve = Person(name: "Eve")
let fay = Person(name: "Fay")
let gay = Person(name: "Gay")
let hope = Person(name: "Hope")
let ivy = Person(name: "Ivy")
let jan = Person(name: "Jan")
abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]
bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]
col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]
dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]
ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]
fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]
gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]
hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]
ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]
jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]
abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]
bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]
cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]
dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]
eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]
fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]
gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]
hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]
ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]
jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]
let guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]
let gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]
engageEveryone(guys)
for guy in guys {
println("\(guy.name) is engaged to \(guy.fiance!.name)")
}
println("Stable = \(isStable(guys, gals))")
jon.swapWith(fred)
println("Stable = \(isStable(guys, gals))")
}
doMarriage()
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Translate the given Tcl code snippet into C without altering its behavior. | package require Tcl 8.5
interp alias {} tcl::mathfunc::pos {} ::lsearch -exact
interp alias {} tcl::mathfunc::nonempty {} ::llength
proc check engaged {
global preferences
set inverse [lreverse $engaged]
set errmsg "%s and %s like each other better than their present partners,\
%s and %s respectively"
dict for {she he} $engaged {
set shelikes [dict get $preferences $she]
set shelikesbetter [lrange $shelikes 0 [expr {pos($shelikes,$he)}]]
set helikes [dict get $preferences $he]
set helikesbetter [lrange $helikes 0 [expr {pos($helikes,$she)}]]
foreach guy $shelikesbetter {
set guysgirl [dict get $inverse $guy]
set guylikes [dict get $preferences $guy]
if {pos($guylikes,$guysgirl) > pos($guylikes,$she)} {
puts [format $errmsg $she $guy $he $guysgirl]
return 0
}
}
foreach gal $helikesbetter {
set galsguy [dict get $engaged $gal]
set gallikes [dict get $preferences $gal]
if {pos($gallikes,$galsguy) > pos($gallikes,$he)} {
puts [format $errmsg $he $gal $she $galsguy]
return 0
}
}
}
return 1
}
proc matchmaker {} {
global guys gals preferences
set guysfree $guys
set engaged {}
array set p $preferences
while {nonempty($guysfree)} {
set guysfree [lassign $guysfree guy]
set p($guy) [set guyslist [lassign $p($guy) gal]]
if {![dict exists $engaged $gal]} {
dict set engaged $gal $guy
puts " $guy and $gal"
continue
}
set fiance [dict get $engaged $gal]
if {pos($p($gal), $fiance) > pos($p($gal), $guy)} {
dict set engaged $gal $guy
puts " $gal dumped $fiance for $guy"
set guy $fiance
}
if {nonempty($p($guy))} {
lappend guysfree $guy
}
}
return $engaged
}
set guys {abe bob col dan ed fred gav hal ian jon}
set gals {abi bea cath dee eve fay gay hope ivy jan}
set preferences {
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}
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}
}
puts "Engagements:"
set engaged [matchmaker]
puts "\nCouples:"
set pfx ""
foreach gal $gals {
puts -nonewline "$pfx $gal is engaged to [dict get $engaged $gal]"
set pfx ",\n"
}
puts "\n"
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
puts "\n\nSwapping two fiances to introduce an error"
set tmp [dict get $engaged [lindex $gals 0]]
dict set engaged [lindex $gals 0] [dict get $engaged [lindex $gals 1]]
dict set engaged [lindex $gals 1] $tmp
foreach gal [lrange $gals 0 1] {
puts " $gal is now engaged to [dict get $engaged $gal]"
}
puts ""
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ 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 },
{ 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 },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Write the same algorithm in C# as shown in this Tcl implementation. | package require Tcl 8.5
interp alias {} tcl::mathfunc::pos {} ::lsearch -exact
interp alias {} tcl::mathfunc::nonempty {} ::llength
proc check engaged {
global preferences
set inverse [lreverse $engaged]
set errmsg "%s and %s like each other better than their present partners,\
%s and %s respectively"
dict for {she he} $engaged {
set shelikes [dict get $preferences $she]
set shelikesbetter [lrange $shelikes 0 [expr {pos($shelikes,$he)}]]
set helikes [dict get $preferences $he]
set helikesbetter [lrange $helikes 0 [expr {pos($helikes,$she)}]]
foreach guy $shelikesbetter {
set guysgirl [dict get $inverse $guy]
set guylikes [dict get $preferences $guy]
if {pos($guylikes,$guysgirl) > pos($guylikes,$she)} {
puts [format $errmsg $she $guy $he $guysgirl]
return 0
}
}
foreach gal $helikesbetter {
set galsguy [dict get $engaged $gal]
set gallikes [dict get $preferences $gal]
if {pos($gallikes,$galsguy) > pos($gallikes,$he)} {
puts [format $errmsg $he $gal $she $galsguy]
return 0
}
}
}
return 1
}
proc matchmaker {} {
global guys gals preferences
set guysfree $guys
set engaged {}
array set p $preferences
while {nonempty($guysfree)} {
set guysfree [lassign $guysfree guy]
set p($guy) [set guyslist [lassign $p($guy) gal]]
if {![dict exists $engaged $gal]} {
dict set engaged $gal $guy
puts " $guy and $gal"
continue
}
set fiance [dict get $engaged $gal]
if {pos($p($gal), $fiance) > pos($p($gal), $guy)} {
dict set engaged $gal $guy
puts " $gal dumped $fiance for $guy"
set guy $fiance
}
if {nonempty($p($guy))} {
lappend guysfree $guy
}
}
return $engaged
}
set guys {abe bob col dan ed fred gav hal ian jon}
set gals {abi bea cath dee eve fay gay hope ivy jan}
set preferences {
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}
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}
}
puts "Engagements:"
set engaged [matchmaker]
puts "\nCouples:"
set pfx ""
foreach gal $gals {
puts -nonewline "$pfx $gal is engaged to [dict get $engaged $gal]"
set pfx ",\n"
}
puts "\n"
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
puts "\n\nSwapping two fiances to introduce an error"
set tmp [dict get $engaged [lindex $gals 0]]
dict set engaged [lindex $gals 0] [dict get $engaged [lindex $gals 1]]
dict set engaged [lindex $gals 1] $tmp
foreach gal [lrange $gals 0 1] {
puts " $gal is now engaged to [dict get $engaged $gal]"
}
puts ""
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Convert this Tcl snippet to C++ and keep its semantics consistent. | package require Tcl 8.5
interp alias {} tcl::mathfunc::pos {} ::lsearch -exact
interp alias {} tcl::mathfunc::nonempty {} ::llength
proc check engaged {
global preferences
set inverse [lreverse $engaged]
set errmsg "%s and %s like each other better than their present partners,\
%s and %s respectively"
dict for {she he} $engaged {
set shelikes [dict get $preferences $she]
set shelikesbetter [lrange $shelikes 0 [expr {pos($shelikes,$he)}]]
set helikes [dict get $preferences $he]
set helikesbetter [lrange $helikes 0 [expr {pos($helikes,$she)}]]
foreach guy $shelikesbetter {
set guysgirl [dict get $inverse $guy]
set guylikes [dict get $preferences $guy]
if {pos($guylikes,$guysgirl) > pos($guylikes,$she)} {
puts [format $errmsg $she $guy $he $guysgirl]
return 0
}
}
foreach gal $helikesbetter {
set galsguy [dict get $engaged $gal]
set gallikes [dict get $preferences $gal]
if {pos($gallikes,$galsguy) > pos($gallikes,$he)} {
puts [format $errmsg $he $gal $she $galsguy]
return 0
}
}
}
return 1
}
proc matchmaker {} {
global guys gals preferences
set guysfree $guys
set engaged {}
array set p $preferences
while {nonempty($guysfree)} {
set guysfree [lassign $guysfree guy]
set p($guy) [set guyslist [lassign $p($guy) gal]]
if {![dict exists $engaged $gal]} {
dict set engaged $gal $guy
puts " $guy and $gal"
continue
}
set fiance [dict get $engaged $gal]
if {pos($p($gal), $fiance) > pos($p($gal), $guy)} {
dict set engaged $gal $guy
puts " $gal dumped $fiance for $guy"
set guy $fiance
}
if {nonempty($p($guy))} {
lappend guysfree $guy
}
}
return $engaged
}
set guys {abe bob col dan ed fred gav hal ian jon}
set gals {abi bea cath dee eve fay gay hope ivy jan}
set preferences {
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}
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}
}
puts "Engagements:"
set engaged [matchmaker]
puts "\nCouples:"
set pfx ""
foreach gal $gals {
puts -nonewline "$pfx $gal is engaged to [dict get $engaged $gal]"
set pfx ",\n"
}
puts "\n"
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
puts "\n\nSwapping two fiances to introduce an error"
set tmp [dict get $engaged [lindex $gals 0]]
dict set engaged [lindex $gals 0] [dict get $engaged [lindex $gals 1]]
dict set engaged [lindex $gals 1] $tmp
foreach gal [lrange $gals 0 1] {
puts " $gal is now engaged to [dict get $engaged $gal]"
}
puts ""
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "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" }
};
const char *women_data[][11] = {
{ "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" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Produce a language-to-language conversion: from Tcl to Python, same semantics. | package require Tcl 8.5
interp alias {} tcl::mathfunc::pos {} ::lsearch -exact
interp alias {} tcl::mathfunc::nonempty {} ::llength
proc check engaged {
global preferences
set inverse [lreverse $engaged]
set errmsg "%s and %s like each other better than their present partners,\
%s and %s respectively"
dict for {she he} $engaged {
set shelikes [dict get $preferences $she]
set shelikesbetter [lrange $shelikes 0 [expr {pos($shelikes,$he)}]]
set helikes [dict get $preferences $he]
set helikesbetter [lrange $helikes 0 [expr {pos($helikes,$she)}]]
foreach guy $shelikesbetter {
set guysgirl [dict get $inverse $guy]
set guylikes [dict get $preferences $guy]
if {pos($guylikes,$guysgirl) > pos($guylikes,$she)} {
puts [format $errmsg $she $guy $he $guysgirl]
return 0
}
}
foreach gal $helikesbetter {
set galsguy [dict get $engaged $gal]
set gallikes [dict get $preferences $gal]
if {pos($gallikes,$galsguy) > pos($gallikes,$he)} {
puts [format $errmsg $he $gal $she $galsguy]
return 0
}
}
}
return 1
}
proc matchmaker {} {
global guys gals preferences
set guysfree $guys
set engaged {}
array set p $preferences
while {nonempty($guysfree)} {
set guysfree [lassign $guysfree guy]
set p($guy) [set guyslist [lassign $p($guy) gal]]
if {![dict exists $engaged $gal]} {
dict set engaged $gal $guy
puts " $guy and $gal"
continue
}
set fiance [dict get $engaged $gal]
if {pos($p($gal), $fiance) > pos($p($gal), $guy)} {
dict set engaged $gal $guy
puts " $gal dumped $fiance for $guy"
set guy $fiance
}
if {nonempty($p($guy))} {
lappend guysfree $guy
}
}
return $engaged
}
set guys {abe bob col dan ed fred gav hal ian jon}
set gals {abi bea cath dee eve fay gay hope ivy jan}
set preferences {
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}
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}
}
puts "Engagements:"
set engaged [matchmaker]
puts "\nCouples:"
set pfx ""
foreach gal $gals {
puts -nonewline "$pfx $gal is engaged to [dict get $engaged $gal]"
set pfx ",\n"
}
puts "\n"
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
puts "\n\nSwapping two fiances to introduce an error"
set tmp [dict get $engaged [lindex $gals 0]]
dict set engaged [lindex $gals 0] [dict get $engaged [lindex $gals 1]]
dict set engaged [lindex $gals 1] $tmp
foreach gal [lrange $gals 0 1] {
puts " $gal is now engaged to [dict get $engaged $gal]"
}
puts ""
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
| import copy
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']}
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']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Rewrite this program in VB while keeping its functionality equivalent to the Tcl version. | package require Tcl 8.5
interp alias {} tcl::mathfunc::pos {} ::lsearch -exact
interp alias {} tcl::mathfunc::nonempty {} ::llength
proc check engaged {
global preferences
set inverse [lreverse $engaged]
set errmsg "%s and %s like each other better than their present partners,\
%s and %s respectively"
dict for {she he} $engaged {
set shelikes [dict get $preferences $she]
set shelikesbetter [lrange $shelikes 0 [expr {pos($shelikes,$he)}]]
set helikes [dict get $preferences $he]
set helikesbetter [lrange $helikes 0 [expr {pos($helikes,$she)}]]
foreach guy $shelikesbetter {
set guysgirl [dict get $inverse $guy]
set guylikes [dict get $preferences $guy]
if {pos($guylikes,$guysgirl) > pos($guylikes,$she)} {
puts [format $errmsg $she $guy $he $guysgirl]
return 0
}
}
foreach gal $helikesbetter {
set galsguy [dict get $engaged $gal]
set gallikes [dict get $preferences $gal]
if {pos($gallikes,$galsguy) > pos($gallikes,$he)} {
puts [format $errmsg $he $gal $she $galsguy]
return 0
}
}
}
return 1
}
proc matchmaker {} {
global guys gals preferences
set guysfree $guys
set engaged {}
array set p $preferences
while {nonempty($guysfree)} {
set guysfree [lassign $guysfree guy]
set p($guy) [set guyslist [lassign $p($guy) gal]]
if {![dict exists $engaged $gal]} {
dict set engaged $gal $guy
puts " $guy and $gal"
continue
}
set fiance [dict get $engaged $gal]
if {pos($p($gal), $fiance) > pos($p($gal), $guy)} {
dict set engaged $gal $guy
puts " $gal dumped $fiance for $guy"
set guy $fiance
}
if {nonempty($p($guy))} {
lappend guysfree $guy
}
}
return $engaged
}
set guys {abe bob col dan ed fred gav hal ian jon}
set gals {abi bea cath dee eve fay gay hope ivy jan}
set preferences {
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}
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}
}
puts "Engagements:"
set engaged [matchmaker]
puts "\nCouples:"
set pfx ""
foreach gal $gals {
puts -nonewline "$pfx $gal is engaged to [dict get $engaged $gal]"
set pfx ",\n"
}
puts "\n"
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
puts "\n\nSwapping two fiances to introduce an error"
set tmp [dict get $engaged [lindex $gals 0]]
dict set engaged [lindex $gals 0] [dict get $engaged [lindex $gals 1]]
dict set engaged [lindex $gals 1] $tmp
foreach gal [lrange $gals 0 1] {
puts " $gal is now engaged to [dict get $engaged $gal]"
}
puts ""
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
| 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 " & _
"_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 " & _
"_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 "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Translate the given Tcl code snippet into Go without altering its behavior. | package require Tcl 8.5
interp alias {} tcl::mathfunc::pos {} ::lsearch -exact
interp alias {} tcl::mathfunc::nonempty {} ::llength
proc check engaged {
global preferences
set inverse [lreverse $engaged]
set errmsg "%s and %s like each other better than their present partners,\
%s and %s respectively"
dict for {she he} $engaged {
set shelikes [dict get $preferences $she]
set shelikesbetter [lrange $shelikes 0 [expr {pos($shelikes,$he)}]]
set helikes [dict get $preferences $he]
set helikesbetter [lrange $helikes 0 [expr {pos($helikes,$she)}]]
foreach guy $shelikesbetter {
set guysgirl [dict get $inverse $guy]
set guylikes [dict get $preferences $guy]
if {pos($guylikes,$guysgirl) > pos($guylikes,$she)} {
puts [format $errmsg $she $guy $he $guysgirl]
return 0
}
}
foreach gal $helikesbetter {
set galsguy [dict get $engaged $gal]
set gallikes [dict get $preferences $gal]
if {pos($gallikes,$galsguy) > pos($gallikes,$he)} {
puts [format $errmsg $he $gal $she $galsguy]
return 0
}
}
}
return 1
}
proc matchmaker {} {
global guys gals preferences
set guysfree $guys
set engaged {}
array set p $preferences
while {nonempty($guysfree)} {
set guysfree [lassign $guysfree guy]
set p($guy) [set guyslist [lassign $p($guy) gal]]
if {![dict exists $engaged $gal]} {
dict set engaged $gal $guy
puts " $guy and $gal"
continue
}
set fiance [dict get $engaged $gal]
if {pos($p($gal), $fiance) > pos($p($gal), $guy)} {
dict set engaged $gal $guy
puts " $gal dumped $fiance for $guy"
set guy $fiance
}
if {nonempty($p($guy))} {
lappend guysfree $guy
}
}
return $engaged
}
set guys {abe bob col dan ed fred gav hal ian jon}
set gals {abi bea cath dee eve fay gay hope ivy jan}
set preferences {
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}
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}
}
puts "Engagements:"
set engaged [matchmaker]
puts "\nCouples:"
set pfx ""
foreach gal $gals {
puts -nonewline "$pfx $gal is engaged to [dict get $engaged $gal]"
set pfx ",\n"
}
puts "\n"
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
puts "\n\nSwapping two fiances to introduce an error"
set tmp [dict get $engaged [lindex $gals 0]]
dict set engaged [lindex $gals 0] [dict get $engaged [lindex $gals 1]]
dict set engaged [lindex $gals 1] $tmp
foreach gal [lrange $gals 0 1] {
puts " $gal is now engaged to [dict get $engaged $gal]"
}
puts ""
puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Change the programming language of this snippet from Ada to C# without modifying what it does. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Main is
package int_vector is new Ada.Containers.Vectors
(Index_Type => Natural, Element_Type => Integer);
use int_vector;
summing_values : Vector := Empty_Vector;
prod : Integer := 1;
sum : Integer := 0;
x : Integer := 5;
y : Integer := -5;
z : Integer := -2;
N : Integer;
begin
N := -3;
while N <= 3**3 loop
summing_values.Append (N);
N := N + 3;
end loop;
N := -7;
while N <= 7 loop
summing_values.Append (N);
N := N + x;
end loop;
for I in 555 .. 550 - y loop
summing_values.Append (I);
end loop;
N := 22;
while N >= -28 loop
summing_values.Append (N);
N := N - 3;
end loop;
for I in 1_927 .. 1_939 loop
summing_values.Append (I);
end loop;
N := x;
while N >= y loop
summing_values.Append (N);
N := N + z;
end loop;
for I in 11**x .. 11**x + 1 loop
summing_values.Append (I);
end loop;
for value of summing_values loop
sum := sum + abs (value);
if abs (prod) < 2**27 and then value /= 0 then
prod := prod * value;
end if;
end loop;
Put_Line ("sum = " & sum'Image);
Put_Line ("prod = " & prod'Image);
end Main;
| using System;
using System.Collections.Generic;
using System.Linq;
public static class LoopsWithMultipleRanges
{
public static void Main() {
int prod = 1;
int sum = 0;
int x = 5;
int y = -5;
int z = -2;
int one = 1;
int three = 3;
int seven = 7;
foreach (int j in Concat(
For(-three, 3.Pow(3), three),
For(-seven, seven, x),
For(555, 550 - y),
For(22, -28, -three),
For(1927, 1939),
For(x, y, z),
For(11.Pow(x), 11.Pow(x) + one)
)) {
sum += Math.Abs(j);
if (Math.Abs(prod) < (1 << 27) && j != 0) prod *= j;
}
Console.WriteLine($" sum = {sum:N0}");
Console.WriteLine($"prod = {prod:N0}");
}
static IEnumerable<int> For(int start, int end, int by = 1) {
for (int i = start; by > 0 ? (i <= end) : (i >= end); i += by) yield return i;
}
static IEnumerable<int> Concat(params IEnumerable<int>[] ranges) => ranges.Aggregate((acc, r) => acc.Concat(r));
static int Pow(this int b, int e) => (int)Math.Pow(b, e);
}
|
Can you help me rewrite this code in C instead of Ada, keeping it the same logically? | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Main is
package int_vector is new Ada.Containers.Vectors
(Index_Type => Natural, Element_Type => Integer);
use int_vector;
summing_values : Vector := Empty_Vector;
prod : Integer := 1;
sum : Integer := 0;
x : Integer := 5;
y : Integer := -5;
z : Integer := -2;
N : Integer;
begin
N := -3;
while N <= 3**3 loop
summing_values.Append (N);
N := N + 3;
end loop;
N := -7;
while N <= 7 loop
summing_values.Append (N);
N := N + x;
end loop;
for I in 555 .. 550 - y loop
summing_values.Append (I);
end loop;
N := 22;
while N >= -28 loop
summing_values.Append (N);
N := N - 3;
end loop;
for I in 1_927 .. 1_939 loop
summing_values.Append (I);
end loop;
N := x;
while N >= y loop
summing_values.Append (N);
N := N + z;
end loop;
for I in 11**x .. 11**x + 1 loop
summing_values.Append (I);
end loop;
for value of summing_values loop
sum := sum + abs (value);
if abs (prod) < 2**27 and then value /= 0 then
prod := prod * value;
end if;
end loop;
Put_Line ("sum = " & sum'Image);
Put_Line ("prod = " & prod'Image);
end Main;
| #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
long prod = 1L, sum = 0L;
void process(int j) {
sum += abs(j);
if (labs(prod) < (1 << 27) && j) prod *= j;
}
long ipow(int n, uint e) {
long pr = n;
int i;
if (e == 0) return 1L;
for (i = 2; i <= e; ++i) pr *= n;
return pr;
}
int main() {
int j;
const int x = 5, y = -5, z = -2;
const int one = 1, three = 3, seven = 7;
long p = ipow(11, x);
for (j = -three; j <= ipow(3, 3); j += three) process(j);
for (j = -seven; j <= seven; j += x) process(j);
for (j = 555; j <= 550 - y; ++j) process(j);
for (j = 22; j >= -28; j -= three) process(j);
for (j = 1927; j <= 1939; ++j) process(j);
for (j = x; j >= y; j -= -z) process(j);
for (j = p; j <= p + one; ++j) process(j);
setlocale(LC_NUMERIC, "");
printf("sum = % 'ld\n", sum);
printf("prod = % 'ld\n", prod);
return 0;
}
|
Translate the given Ada code snippet into C++ without altering its behavior. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Main is
package int_vector is new Ada.Containers.Vectors
(Index_Type => Natural, Element_Type => Integer);
use int_vector;
summing_values : Vector := Empty_Vector;
prod : Integer := 1;
sum : Integer := 0;
x : Integer := 5;
y : Integer := -5;
z : Integer := -2;
N : Integer;
begin
N := -3;
while N <= 3**3 loop
summing_values.Append (N);
N := N + 3;
end loop;
N := -7;
while N <= 7 loop
summing_values.Append (N);
N := N + x;
end loop;
for I in 555 .. 550 - y loop
summing_values.Append (I);
end loop;
N := 22;
while N >= -28 loop
summing_values.Append (N);
N := N - 3;
end loop;
for I in 1_927 .. 1_939 loop
summing_values.Append (I);
end loop;
N := x;
while N >= y loop
summing_values.Append (N);
N := N + z;
end loop;
for I in 11**x .. 11**x + 1 loop
summing_values.Append (I);
end loop;
for value of summing_values loop
sum := sum + abs (value);
if abs (prod) < 2**27 and then value /= 0 then
prod := prod * value;
end if;
end loop;
Put_Line ("sum = " & sum'Image);
Put_Line ("prod = " & prod'Image);
end Main;
| #include <iostream>
#include <cmath>
#include <vector>
using std::abs;
using std::cout;
using std::pow;
using std::vector;
int main()
{
int prod = 1,
sum = 0,
x = 5,
y = -5,
z = -2,
one = 1,
three = 3,
seven = 7;
auto summingValues = vector<int>{};
for(int n = -three; n <= pow(3, 3); n += three)
summingValues.push_back(n);
for(int n = -seven; n <= seven; n += x)
summingValues.push_back(n);
for(int n = 555; n <= 550 - y; ++n)
summingValues.push_back(n);
for(int n = 22; n >= -28; n -= three)
summingValues.push_back(n);
for(int n = 1927; n <= 1939; ++n)
summingValues.push_back(n);
for(int n = x; n >= y; n += z)
summingValues.push_back(n);
for(int n = pow(11, x); n <= pow(11, x) + one; ++n)
summingValues.push_back(n);
for(auto j : summingValues)
{
sum += abs(j);
if(abs(prod) < pow(2, 27) && j != 0)
prod *= j;
}
cout << "sum = " << sum << "\n";
cout << "prod = " << prod << "\n";
}
|
Port the following code from Ada to Go with equivalent syntax and logic. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Main is
package int_vector is new Ada.Containers.Vectors
(Index_Type => Natural, Element_Type => Integer);
use int_vector;
summing_values : Vector := Empty_Vector;
prod : Integer := 1;
sum : Integer := 0;
x : Integer := 5;
y : Integer := -5;
z : Integer := -2;
N : Integer;
begin
N := -3;
while N <= 3**3 loop
summing_values.Append (N);
N := N + 3;
end loop;
N := -7;
while N <= 7 loop
summing_values.Append (N);
N := N + x;
end loop;
for I in 555 .. 550 - y loop
summing_values.Append (I);
end loop;
N := 22;
while N >= -28 loop
summing_values.Append (N);
N := N - 3;
end loop;
for I in 1_927 .. 1_939 loop
summing_values.Append (I);
end loop;
N := x;
while N >= y loop
summing_values.Append (N);
N := N + z;
end loop;
for I in 11**x .. 11**x + 1 loop
summing_values.Append (I);
end loop;
for value of summing_values loop
sum := sum + abs (value);
if abs (prod) < 2**27 and then value /= 0 then
prod := prod * value;
end if;
end loop;
Put_Line ("sum = " & sum'Image);
Put_Line ("prod = " & prod'Image);
end Main;
| package main
import "fmt"
func pow(n int, e uint) int {
if e == 0 {
return 1
}
prod := n
for i := uint(2); i <= e; i++ {
prod *= n
}
return prod
}
func abs(n int) int {
if n >= 0 {
return n
}
return -n
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return " " + s
}
return "-" + s
}
func main() {
prod := 1
sum := 0
const (
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
)
p := pow(11, x)
var j int
process := func() {
sum += abs(j)
if abs(prod) < (1<<27) && j != 0 {
prod *= j
}
}
for j = -three; j <= pow(3, 3); j += three {
process()
}
for j = -seven; j <= seven; j += x {
process()
}
for j = 555; j <= 550-y; j++ {
process()
}
for j = 22; j >= -28; j -= three {
process()
}
for j = 1927; j <= 1939; j++ {
process()
}
for j = x; j >= y; j -= -z {
process()
}
for j = p; j <= p+one; j++ {
process()
}
fmt.Println("sum = ", commatize(sum))
fmt.Println("prod = ", commatize(prod))
}
|
Write the same code in Java as shown below in Ada. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Main is
package int_vector is new Ada.Containers.Vectors
(Index_Type => Natural, Element_Type => Integer);
use int_vector;
summing_values : Vector := Empty_Vector;
prod : Integer := 1;
sum : Integer := 0;
x : Integer := 5;
y : Integer := -5;
z : Integer := -2;
N : Integer;
begin
N := -3;
while N <= 3**3 loop
summing_values.Append (N);
N := N + 3;
end loop;
N := -7;
while N <= 7 loop
summing_values.Append (N);
N := N + x;
end loop;
for I in 555 .. 550 - y loop
summing_values.Append (I);
end loop;
N := 22;
while N >= -28 loop
summing_values.Append (N);
N := N - 3;
end loop;
for I in 1_927 .. 1_939 loop
summing_values.Append (I);
end loop;
N := x;
while N >= y loop
summing_values.Append (N);
N := N + z;
end loop;
for I in 11**x .. 11**x + 1 loop
summing_values.Append (I);
end loop;
for value of summing_values loop
sum := sum + abs (value);
if abs (prod) < 2**27 and then value /= 0 then
prod := prod * value;
end if;
end loop;
Put_Line ("sum = " & sum'Image);
Put_Line ("prod = " & prod'Image);
end Main;
| import java.util.ArrayList;
import java.util.List;
public class LoopsWithMultipleRanges {
private static long sum = 0;
private static long prod = 1;
public static void main(String[] args) {
long x = 5;
long y = -5;
long z = -2;
long one = 1;
long three = 3;
long seven = 7;
List<Long> jList = new ArrayList<>();
for ( long j = -three ; j <= pow(3, 3) ; j += three ) jList.add(j);
for ( long j = -seven ; j <= seven ; j += x ) jList.add(j);
for ( long j = 555 ; j <= 550-y ; j += 1 ) jList.add(j);
for ( long j = 22 ; j >= -28 ; j += -three ) jList.add(j);
for ( long j = 1927 ; j <= 1939 ; j += 1 ) jList.add(j);
for ( long j = x ; j >= y ; j += z ) jList.add(j);
for ( long j = pow(11, x) ; j <= pow(11, x) + one ; j += 1 ) jList.add(j);
List<Long> prodList = new ArrayList<>();
for ( long j : jList ) {
sum += Math.abs(j);
if ( Math.abs(prod) < pow(2, 27) && j != 0 ) {
prodList.add(j);
prod *= j;
}
}
System.out.printf(" sum = %,d%n", sum);
System.out.printf("prod = %,d%n", prod);
System.out.printf("j values = %s%n", jList);
System.out.printf("prod values = %s%n", prodList);
}
private static long pow(long base, long exponent) {
return (long) Math.pow(base, exponent);
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Main is
package int_vector is new Ada.Containers.Vectors
(Index_Type => Natural, Element_Type => Integer);
use int_vector;
summing_values : Vector := Empty_Vector;
prod : Integer := 1;
sum : Integer := 0;
x : Integer := 5;
y : Integer := -5;
z : Integer := -2;
N : Integer;
begin
N := -3;
while N <= 3**3 loop
summing_values.Append (N);
N := N + 3;
end loop;
N := -7;
while N <= 7 loop
summing_values.Append (N);
N := N + x;
end loop;
for I in 555 .. 550 - y loop
summing_values.Append (I);
end loop;
N := 22;
while N >= -28 loop
summing_values.Append (N);
N := N - 3;
end loop;
for I in 1_927 .. 1_939 loop
summing_values.Append (I);
end loop;
N := x;
while N >= y loop
summing_values.Append (N);
N := N + z;
end loop;
for I in 11**x .. 11**x + 1 loop
summing_values.Append (I);
end loop;
for value of summing_values loop
sum := sum + abs (value);
if abs (prod) < 2**27 and then value /= 0 then
prod := prod * value;
end if;
end loop;
Put_Line ("sum = " & sum'Image);
Put_Line ("prod = " & prod'Image);
end Main;
| from itertools import chain
prod, sum_, x, y, z, one,three,seven = 1, 0, 5, -5, -2, 1, 3, 7
def _range(x, y, z=1):
return range(x, y + (1 if z > 0 else -1), z)
print(f'list(_range(x, y, z)) = {list(_range(x, y, z))}')
print(f'list(_range(-seven, seven, x)) = {list(_range(-seven, seven, x))}')
for j in chain(_range(-three, 3**3, three), _range(-seven, seven, x),
_range(555, 550 - y), _range(22, -28, -three),
_range(1927, 1939), _range(x, y, z),
_range(11**x, 11**x + 1)):
sum_ += abs(j)
if abs(prod) < 2**27 and (j != 0):
prod *= j
print(f' sum= {sum_}\nprod= {prod}')
|
Translate the given Ada code snippet into VB without altering its behavior. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Main is
package int_vector is new Ada.Containers.Vectors
(Index_Type => Natural, Element_Type => Integer);
use int_vector;
summing_values : Vector := Empty_Vector;
prod : Integer := 1;
sum : Integer := 0;
x : Integer := 5;
y : Integer := -5;
z : Integer := -2;
N : Integer;
begin
N := -3;
while N <= 3**3 loop
summing_values.Append (N);
N := N + 3;
end loop;
N := -7;
while N <= 7 loop
summing_values.Append (N);
N := N + x;
end loop;
for I in 555 .. 550 - y loop
summing_values.Append (I);
end loop;
N := 22;
while N >= -28 loop
summing_values.Append (N);
N := N - 3;
end loop;
for I in 1_927 .. 1_939 loop
summing_values.Append (I);
end loop;
N := x;
while N >= y loop
summing_values.Append (N);
N := N + z;
end loop;
for I in 11**x .. 11**x + 1 loop
summing_values.Append (I);
end loop;
for value of summing_values loop
sum := sum + abs (value);
if abs (prod) < 2**27 and then value /= 0 then
prod := prod * value;
end if;
end loop;
Put_Line ("sum = " & sum'Image);
Put_Line ("prod = " & prod'Image);
end Main;
| Dim prod As Long, sum As Long
Public Sub LoopsWithMultipleRanges()
Dim x As Integer, y As Integer, z As Integer, one As Integer, three As Integer, seven As Integer, j As Long
prod = 1
sum = 0
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
For j = -three To pow(3, 3) Step three: Call process(j): Next j
For j = -seven To seven Step x: Call process(j): Next j
For j = 555 To 550 - y: Call process(j): Next j
For j = 22 To -28 Step -three: Call process(j): Next j
For j = 1927 To 1939: Call process(j): Next j
For j = x To y Step z: Call process(j): Next j
For j = pow(11, x) To pow(11, x) + one: Call process(j): Next j
Debug.Print " sum= " & Format(sum, "#,##0")
Debug.Print "prod= " & Format(prod, "#,##0")
End Sub
Private Function pow(x As Long, y As Integer) As Long
pow = WorksheetFunction.Power(x, y)
End Function
Private Sub process(x As Long)
sum = sum + Abs(x)
If Abs(prod) < pow(2, 27) And x <> 0 Then prod = prod * x
End Sub
|
Translate the given AutoHotKey code snippet into C without altering its behavior. | for_J(doFunction, start, stop, step:=1){
j := start
while (j<=stop) && (start<=stop) && (step>0)
%doFunction%(j), j+=step
while (j>=stop) && (start>stop) && (step<0)
%doFunction%(j), j+=step
}
| #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
long prod = 1L, sum = 0L;
void process(int j) {
sum += abs(j);
if (labs(prod) < (1 << 27) && j) prod *= j;
}
long ipow(int n, uint e) {
long pr = n;
int i;
if (e == 0) return 1L;
for (i = 2; i <= e; ++i) pr *= n;
return pr;
}
int main() {
int j;
const int x = 5, y = -5, z = -2;
const int one = 1, three = 3, seven = 7;
long p = ipow(11, x);
for (j = -three; j <= ipow(3, 3); j += three) process(j);
for (j = -seven; j <= seven; j += x) process(j);
for (j = 555; j <= 550 - y; ++j) process(j);
for (j = 22; j >= -28; j -= three) process(j);
for (j = 1927; j <= 1939; ++j) process(j);
for (j = x; j >= y; j -= -z) process(j);
for (j = p; j <= p + one; ++j) process(j);
setlocale(LC_NUMERIC, "");
printf("sum = % 'ld\n", sum);
printf("prod = % 'ld\n", prod);
return 0;
}
|
Translate the given AutoHotKey code snippet into C# without altering its behavior. | for_J(doFunction, start, stop, step:=1){
j := start
while (j<=stop) && (start<=stop) && (step>0)
%doFunction%(j), j+=step
while (j>=stop) && (start>stop) && (step<0)
%doFunction%(j), j+=step
}
| using System;
using System.Collections.Generic;
using System.Linq;
public static class LoopsWithMultipleRanges
{
public static void Main() {
int prod = 1;
int sum = 0;
int x = 5;
int y = -5;
int z = -2;
int one = 1;
int three = 3;
int seven = 7;
foreach (int j in Concat(
For(-three, 3.Pow(3), three),
For(-seven, seven, x),
For(555, 550 - y),
For(22, -28, -three),
For(1927, 1939),
For(x, y, z),
For(11.Pow(x), 11.Pow(x) + one)
)) {
sum += Math.Abs(j);
if (Math.Abs(prod) < (1 << 27) && j != 0) prod *= j;
}
Console.WriteLine($" sum = {sum:N0}");
Console.WriteLine($"prod = {prod:N0}");
}
static IEnumerable<int> For(int start, int end, int by = 1) {
for (int i = start; by > 0 ? (i <= end) : (i >= end); i += by) yield return i;
}
static IEnumerable<int> Concat(params IEnumerable<int>[] ranges) => ranges.Aggregate((acc, r) => acc.Concat(r));
static int Pow(this int b, int e) => (int)Math.Pow(b, e);
}
|
Port the following code from AutoHotKey to C++ with equivalent syntax and logic. | for_J(doFunction, start, stop, step:=1){
j := start
while (j<=stop) && (start<=stop) && (step>0)
%doFunction%(j), j+=step
while (j>=stop) && (start>stop) && (step<0)
%doFunction%(j), j+=step
}
| #include <iostream>
#include <cmath>
#include <vector>
using std::abs;
using std::cout;
using std::pow;
using std::vector;
int main()
{
int prod = 1,
sum = 0,
x = 5,
y = -5,
z = -2,
one = 1,
three = 3,
seven = 7;
auto summingValues = vector<int>{};
for(int n = -three; n <= pow(3, 3); n += three)
summingValues.push_back(n);
for(int n = -seven; n <= seven; n += x)
summingValues.push_back(n);
for(int n = 555; n <= 550 - y; ++n)
summingValues.push_back(n);
for(int n = 22; n >= -28; n -= three)
summingValues.push_back(n);
for(int n = 1927; n <= 1939; ++n)
summingValues.push_back(n);
for(int n = x; n >= y; n += z)
summingValues.push_back(n);
for(int n = pow(11, x); n <= pow(11, x) + one; ++n)
summingValues.push_back(n);
for(auto j : summingValues)
{
sum += abs(j);
if(abs(prod) < pow(2, 27) && j != 0)
prod *= j;
}
cout << "sum = " << sum << "\n";
cout << "prod = " << prod << "\n";
}
|
Can you help me rewrite this code in Java instead of AutoHotKey, keeping it the same logically? | for_J(doFunction, start, stop, step:=1){
j := start
while (j<=stop) && (start<=stop) && (step>0)
%doFunction%(j), j+=step
while (j>=stop) && (start>stop) && (step<0)
%doFunction%(j), j+=step
}
| import java.util.ArrayList;
import java.util.List;
public class LoopsWithMultipleRanges {
private static long sum = 0;
private static long prod = 1;
public static void main(String[] args) {
long x = 5;
long y = -5;
long z = -2;
long one = 1;
long three = 3;
long seven = 7;
List<Long> jList = new ArrayList<>();
for ( long j = -three ; j <= pow(3, 3) ; j += three ) jList.add(j);
for ( long j = -seven ; j <= seven ; j += x ) jList.add(j);
for ( long j = 555 ; j <= 550-y ; j += 1 ) jList.add(j);
for ( long j = 22 ; j >= -28 ; j += -three ) jList.add(j);
for ( long j = 1927 ; j <= 1939 ; j += 1 ) jList.add(j);
for ( long j = x ; j >= y ; j += z ) jList.add(j);
for ( long j = pow(11, x) ; j <= pow(11, x) + one ; j += 1 ) jList.add(j);
List<Long> prodList = new ArrayList<>();
for ( long j : jList ) {
sum += Math.abs(j);
if ( Math.abs(prod) < pow(2, 27) && j != 0 ) {
prodList.add(j);
prod *= j;
}
}
System.out.printf(" sum = %,d%n", sum);
System.out.printf("prod = %,d%n", prod);
System.out.printf("j values = %s%n", jList);
System.out.printf("prod values = %s%n", prodList);
}
private static long pow(long base, long exponent) {
return (long) Math.pow(base, exponent);
}
}
|
Convert the following code from AutoHotKey to Python, ensuring the logic remains intact. | for_J(doFunction, start, stop, step:=1){
j := start
while (j<=stop) && (start<=stop) && (step>0)
%doFunction%(j), j+=step
while (j>=stop) && (start>stop) && (step<0)
%doFunction%(j), j+=step
}
| from itertools import chain
prod, sum_, x, y, z, one,three,seven = 1, 0, 5, -5, -2, 1, 3, 7
def _range(x, y, z=1):
return range(x, y + (1 if z > 0 else -1), z)
print(f'list(_range(x, y, z)) = {list(_range(x, y, z))}')
print(f'list(_range(-seven, seven, x)) = {list(_range(-seven, seven, x))}')
for j in chain(_range(-three, 3**3, three), _range(-seven, seven, x),
_range(555, 550 - y), _range(22, -28, -three),
_range(1927, 1939), _range(x, y, z),
_range(11**x, 11**x + 1)):
sum_ += abs(j)
if abs(prod) < 2**27 and (j != 0):
prod *= j
print(f' sum= {sum_}\nprod= {prod}')
|
Change the following AutoHotKey code into VB without altering its purpose. | for_J(doFunction, start, stop, step:=1){
j := start
while (j<=stop) && (start<=stop) && (step>0)
%doFunction%(j), j+=step
while (j>=stop) && (start>stop) && (step<0)
%doFunction%(j), j+=step
}
| Dim prod As Long, sum As Long
Public Sub LoopsWithMultipleRanges()
Dim x As Integer, y As Integer, z As Integer, one As Integer, three As Integer, seven As Integer, j As Long
prod = 1
sum = 0
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
For j = -three To pow(3, 3) Step three: Call process(j): Next j
For j = -seven To seven Step x: Call process(j): Next j
For j = 555 To 550 - y: Call process(j): Next j
For j = 22 To -28 Step -three: Call process(j): Next j
For j = 1927 To 1939: Call process(j): Next j
For j = x To y Step z: Call process(j): Next j
For j = pow(11, x) To pow(11, x) + one: Call process(j): Next j
Debug.Print " sum= " & Format(sum, "#,##0")
Debug.Print "prod= " & Format(prod, "#,##0")
End Sub
Private Function pow(x As Long, y As Integer) As Long
pow = WorksheetFunction.Power(x, y)
End Function
Private Sub process(x As Long)
sum = sum + Abs(x)
If Abs(prod) < pow(2, 27) And x <> 0 Then prod = prod * x
End Sub
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.