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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews