Solving the Stable Marriage problem in Erlang

Yan Cui

I help clients go faster for less using serverless technologies.

Whilst talking with an ex-colleague, a question came up on how to implement the Stable Marriage problem using a message passing approach. Naturally, I wanted to answer that question with Erlang!

Let’s first dissect the problem and decide what processes we need and how they need to interact with one another.

The stable marriage problem is commonly stated as:

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 together 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”. (It is assumed that the participants are binary gendered and that marriages are not same-sex).

From the problem description, we can see that we need:

  • a module for man
  • a module for woman
  • a module for orchestrating the experiment

In terms of interaction between the different modules, I imagined something along the line of the following:

image

The proposal communication needs to be synchronous* as the man cannot proceed until he gets an answer for his proposal. But all other communications can be asynchronous.

(* remember, a synchronous call in OTP-sense is not the same as a synchronous call in Java/C# where the calling thread is blocked.

In this case the communication still happens via asynchronous message passing, but the calling process asynchronously waits for a reply before moving on)

From here, the implementation itself is pretty straight forward.

And using the test data from Rosetta Code, you can have a module that sets up the test, which I’ve called stable_marriage here.

Compile and run the code gives the following output:

image

You can get the full source code for this solution on github.

Enjoy!

Links

Repo for solution

Rosetta Code test data


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


Leave a Comment

Your email address will not be published. Required fields are marked *