Program to solve Stable marriage problem in C.

Given n men and n women, where each person has ranked all members of the opposite sex with a unique number between 1 and n in order of preference, marry the men and women off such that there are no two people of opposite sex who would both rather have each other than their current partners. If there are no such people, all the marriages are “stable”.

#include<stdio.h>

int b[100][100],g[100][100],s[2][100];

main()
{
int n,i,j,k;

FILE *fp;

fp= fopen("prefer.dat","r");

fscanf(fp,"%d",&n);

printf(" the number of couples %d:\n",n);
printf("PREFERENCE OF MALE\n");
for(i=0;i<n;i++)

{
for(j=0;j<n+1;j++)
{
fscanf(fp,"%d",&b[j][i]);
printf("%d\t",b[j][i]);
}
printf("\n");
}
printf("PREFERENCE OF FEMALE\n");
for(i=0;i<n;i++)
{
for(j=0;j<n+1;j++)
{
fscanf(fp,"%d",&g[j][i]);
printf("%d\t",g[j][i]);
}
printf("\n");
}


for(i=0;i<n;i++){
s[0][i]=b[0][i];
s[1][i]=b[1][i];
match(i,n);
}
printf("FINAL OUTPUT\n");
for(i=0;i<n;i++){
printf("%d      %d\n",s[0][i],s[1][i]);
}
}



int match(int i,int n)
{
int j,k,h,t,m;
for(j=0;j<=i;j++)
{
for(m=0;m<=i;m++)
{
if(m!=j&&s[1][m]==s[1][j])
{
k=s[1][j];
for(h=1;h<n;h++)
{
if (g[h][k-1]==j+1)
{
for (t=1;t<n;t++)
if (k==b[t][m])break;
s[1][m]=b[++t][m];
match(i,n);
return;
}
else if(g[h][k-1]==m+1)
{
for (t=1;t<n;t++)
if (k==b[t][j])break;
s[1][j]=b[++t][j];
match(i,n);
return;
}
}

}
}
}return;
}
Advertisements

7 thoughts on “Program to solve Stable marriage problem in C.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s