×

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people of the same sex who would choose to be together over their current relationships. Each person has listed their preferences for each member of the other sex in order.If none of these exist, all marriages are deemed to be "stable."
The stable marriage problem is a classic problem in computer science and economics. Finding the perfect match between two sets of elements is a problem, often referred to as men and women.
The goal of the problem is to find a stable set of matches, that is, a set of matches such that no two people prefer each other over their current match. Several algorithms , such as the Gale-Shapley algorithm, have been developed to solve this problem.
In Java, the Gale-Shapley algorithm can be used to solve the stable marriage problem. The algorithm works by having each man and woman rank each other and then iterating over the set of pairs. For each pair, the man and woman compare their rankings, and the man proposes to the woman if he ranks her higher than his current match. The woman then either accepts or rejects the proposal. The algorithm continues until all pairs are stable. The "stable matching problem" requires that two sets of people, men and women, be stably matched to one another. The Gale-Shapley algorithm is an algorithm that resolves this problem. It was initially put up in 1962 by David Gale and Lloyd Shapley.The algorithm works by having each man propose to the woman he prefers, and each woman accepts the highest-ranking proposal she receives. This process continues until each man is matched to a woman and each woman is matched to a man. The matching is said to be stable if there is no pair of people who prefer each other over the people they are matched with.

Example 1
Alice and Bob are both single and looking to get married. Both have a list of potential partners, ranked in order of preference. Alice's list of preferences is Bob, Dave, Joe, and Carl; Bob's list of preferences is Alice, Joe, Dave, and Carl.
Assuming that both Alice and Bob are honest about their preferences, the stable marriage problem can be solved by having Alice and Bob go through the following steps:

  1. Alice proposes to Bob, who accepts.
  2. Dave proposes to Alice, who rejects him.
  3. Joe proposes to Alice, who rejects him.
  4. Carl proposes to Alice, who rejects him.
  5. Joe proposes to Bob, who rejects him.
  6. Dave proposes to Bob, who accepts.
    As a result, Alice and Bob are now married, and Dave and Joe remain single. This is a stable marriage because no two people would benefit from switching partners since Alice and Bob prefer each other to the other two potential partners.

Example 2

Example:

John, Mary, Bob, and Jane are four individuals who need to find partners. John and Mary prefer each other over Bob and Jane, while Bob and Jane prefer each other over John and Mary.

John: Mary, Bob, Jane
Mary: John, Bob, Jane
Bob: Jane, Mary, John
Jane: Bob, Mary, John
In this case, the stable marriage problem can be solved by having John and Mary pair off while Bob and Jane pair off. This solution is stable, as neither John nor Mary would prefer Bob or Jane over each other, and neither Bob nor Jane would prefer John or Mary over each other.

Using Gale Shapley Algorithm

The goal is to cycle through every available free man as long as there are accessible free men. Every free man visits every woman on his preference list in the order they are listed. He asks each lady he approaches if she is available, and if she is, they become engaged. If the woman is not free, she can reject him or break off her engagement with the man, depending on her preference list. Therefore, a previously established engagement may be broken if a woman has a better option. The Gale-Shapley algorithm has an O time complexity (n2).

Pseudo Code

// Function to calculate Shapley value
FUNCTION ShapleyValue(players, contributions):
  // Initialize the Shapley value of each player to 0
  SET ShapleyValues FOR players TO 0
  // Loop through all possible permutations of players
  FOR EACH permutation IN players:
    // Calculate the contribution to the total
    // made by the players in this permutation
    SET contribution TO contributions[permutation]
    // Calculate the marginal contribution of each player
    // in this permutation
    FOR EACH player IN permutation:
      SET marginalContribution TO contribution - contributions[permutation without player]  
    // Add the marginal contribution of each player
    // to their Shapley value
    FOR EACH player IN permutation:
    SET ShapleyValues[player] TO ShapleyValues[player] + marginal contribution
      
  // Divide the Shapley values of each player
  // by the total number of permutations
  FOR EACH player IN players:
    SET ShapleyValues[player] TO ShapleyValues[player] / PERMUTATIONS(players)
   RETURN SjapleyValues

Program
File Name : StableMarriage.java

// Finding the stable marriages using GaleShapley Algorithm
// importing the required packages
import java. util.*;
// Main class declaration 
class StableMarriage
{
// Number of Men or Women
// static declaration of number of women or men 
static int n = 4;
//  wPrefersM1 function returns true if a woman 'w' prefers a man 'm1.' 
static boolean wPrefersM1(int pre[][], int w,int m, int m1)
{
	// Check if w prefers m over her current engagement m1
	for (int j = 0; j < n; j++)
	{
		// If m1 comes before m in the list of w,  then w prefers her current engagement
		if (pre[w][j] == m1)
			return true;
		if (pre[w][j] == m)
		return false;
	}
	return false;
}
// static function declaration to find the stableMarriage . Static functions does not require objects 
static void stableMarriage(int pre[][])
{	
	// integer array to store all the partners of women w
	int wPartner[] = new int[n];
	boolean mFree[] = new boolean[n];
	Arrays.fill(wPartner, -1);
	int freeCount = n;
	while (freeCount > 0)
	{
		// Pick the first free man
		int m;
		// for loop to check whether the men at index m is free or not
		for (m = 0; m < n; m++)
			if (mFree[m] == false)
				break;
		// Go to each woman one by one by m's preferences. This is M, the chosen free guy.
		for (int j = 0; j < n && mFree[m] == false; j++)
		{
			int w = pre[m][j];
			// if the partner of w is not there   
			if (wPartner[w - n] == -1)
			{
				wPartner[w - n] = m;
				mFree[m] = true;
				freeCount--;
			}
			// If w is not free
			else 
			{
				// Find current engagement of w
				int m1 = wPartner[w - n];
			// if the woman w prefers m1, then
				if (wPrefersM1(pre, w, m, m1) == false)
				{
					wPartner[w - n] = m;
					mFree[m] = true;
					mFree[m1] = false;
				}
			} // Else block
		} 
	} //  main while loop block
// Printing the solution
System.out.println("Woman  Man");
// for loop to print the solution
for (int j = 0; j < n; j++)
{
	System.out.print(" ");
	System.out.println(j + n + "	 " + wPartner[j]);
}
}
// Main section of the program, from where execution begins
public static void main(String[] args)
{
	// static declaration of 2- D array to store all the data of women and men
	int pre[][] = new int[][]{{7, 5, 6, 4},
						{5, 4, 6, 7},											{4, 5, 6, 4},
						{5, 5, 6, 7},
						{0, 1, 2, 3},
						{0, 1, 1, 3},
						{0, 2, 2, 3},
						{0,1,3,3}};	
	// calling the function to find stable marriages 
	stableMarriage(pre);
}
}

Output

Woman  Man
 4	 2
 5	 1
 6	 3
 7	 0


Explanation
All men and women are initially unengaged or free. Each male will present the ladies on his preference list (ranked from highest to lowest), and while iterating the list for each woman, determine whether she is free and, if so, engage her. If not, it means that she has already accepted a proposal from another man. In that case, she can either dump the first man and accept the current man's offer (this will only occur if the current man is preferred over the first man on her list of preferences), or she can decide not to dump the man and let the current man try his luck with the other woman on his list.


Related Topics

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.