ryanzidago

ryanzidago

I’m trying to implement the Gale-Shapley algoritm in Elixir to solve the Stable Marriage Problem.

I managed to come up with an implementation of the algorithm in Ruby but I can’t achieve a solution with Elixir/the functional programming way; especially due to immutability.

Note that I’m trying to first implement this algorithm sequentially (without actors) so an implementation like this is not what I’m trying to achieve right now.

I have found this implementation in Elixir, but it does not pass Rosetta Code’s test case.

Here’s what I have so far.

How would you tackle this problem? :thinking:

Showing Posts 1 to 10

APB9785

APB9785

Creator of ECSx

It looks like you’re doing it very similarly to how I would. Is your code failing the tests?

ryanzidago

ryanzidago OP

Yes it is failing the Rosetta Code test case (the one with the real names, not just the letters).

I think it’s because if a man is not available, I still pop his favorite woman from his preference list, even though he did not technically proposed to her. A man propose to a woman only if he is available.

I tried to not pop the favorite woman out of the preference list for this case, but it still did not work.

ityonemo

ityonemo

this might help:

especially note:

A digraph is a mutable data structure.

Also unrelated pedantry (sorry, this is a pet obession of mine) is_ functions should be reserved for guards; postifx sigil ...? (like ruby) is the idiomatic way to indicate a boolean function in elixir.

APB9785

APB9785

Creator of ECSx

What is stopping you from skipping over the unavailable men each round and not considering their favored women at all?

Also, I agree with @ityonemo that the is_ prefix should be replaced by a ? suffix for booleans.

ryanzidago

ryanzidago OP

I would like to avoid relying on ETS right now and would rather try to do it the functional way.

But using digraph for solving this problem is definitely something that I’d like to explore later.

ryanzidago

ryanzidago OP

I did try like this:

defmodule StableMarriage do
  def match(men, women, state \\ %{}, is_stable \\ false)

  def match(men, _women, state, true) do
    state
    |> Map.to_list()
    |> Enum.slice(0..(length(Map.keys(men)) - 1))
  end

  def match(men, women, state, false) do
    {new_men, state} =
      Enum.reduce(men, {men, state}, fn
        {m1, [w | preferences]}, {men, state} ->
          if m1_single? = !state[m1] do
            w_single? = !state[w]
            m2 = if w_single?, do: nil, else: state[w]

            new_state =
              case {m1_single?, w_single?, m1_prefered_to_m2?(women, w, m1, m2)} do
                {true, true, true} -> state |> Map.put(m1, w) |> Map.put(w, m1)
                {true, false, true} -> state |> Map.delete(m2) |> Map.put(m1, w) |> Map.put(w, m1)
                _ -> state
              end

            {_men = %{men | m1 => preferences}, new_state}
          else
            {men, state}
          end
      end)

    match(new_men, women, state, is_stable(men, state))
  end

  def m1_prefered_to_m2?(_women, _woman, _m1, nil) do
    true
  end

  def m1_prefered_to_m2?(women, woman, m1, m2) do
    Enum.find_index(women[woman], &(&1 == m1)) <
      Enum.find_index(women[woman], &(&1 == m2))
  end

  def is_stable(men, state) do
    length(Map.keys(men)) * 2 == length(Map.keys(state))
  end
end

But surprisingly, I get some pairs in the wrong order/or in doubles in the final result while some other pairs are missing:

     test/stable_marriage_test.exs:4
     Assertion with in failed
     code:  assert {"jon", "abi"} in matches
     left:  {"jon", "abi"}
     right: [{"abe", "ivy"}, {"abi", "jon"}, {"bea", "fred"}, {"bob", "cath"}, {"cath", "bob"}, {"col", "dee"}, {"dan", "fay"}, {"dee", "col"}, {"ed", "jan"}, {"eve", "hal"}]
     stacktrace:
       test/stable_marriage_test.exs:61: (test)
APB9785

APB9785

Creator of ECSx

That looks to be from this code:

case {m1_single?, w_single?, m1_prefered_to_m2?(women, w, m1, m2)} do
  {true, true, true} -> state |> Map.put(m1, w) |> Map.put(w, m1)
  {true, false, true} -> state |> Map.delete(m2) |> Map.put(m1, w) |> Map.put(w, m1)
  _ -> state
end

Where sometimes you are using the man as the key (and woman as value) and other times you are adding the woman as the key (and man as value). I think you need to keep that consistent.

ryanzidago

ryanzidago OP

The state variable holds the pairs from man to woman and woman to man. So if “a” and “z” forms a couple, the state map will have %{"a" => "z", "z" => "a"}. I need this to be able to find the current fiancé of any given woman.

ryanzidago

ryanzidago OP

But thank you for pointing me in the right direction, I actually found the culprit code:

  def match(men, _women, state, true) do
    state
    |> Map.to_list()
    |> Enum.slice(0..(length(Map.keys(men)) - 1))
  end

Since I have both men and women in state, I cannot simply discard the state to only keep men-pairs like this. This works for the first test case but not the second one.

I ended up changing it like so:

  def match(men, _women, state, true) do
    men_keys = Map.keys(men)
    for {k, v} <- state, k in men_keys, do: {k, v}
  end

So from the state, I only keep the men keys and put them into a tuple with thier fiancée.

And now the Rosetta Code’s test case passes!

:pray:

APB9785

APB9785

Creator of ECSx

Nice work!

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews