Skip to content

Commit e8fdf02

Browse files
kenpowerjiegillet
authored andcommitted
Stable marriage implementation in Scala (#460)
* stable marrige implementation in scala * refactor implementation details out of main * change from a ListBuffer to a Queue for bachelors
1 parent 9b2da4e commit e8fdf02

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import scala.collection.mutable._
2+
3+
object StableMarriage {
4+
5+
var bachelors = Queue[Man]()
6+
7+
case class Man(name: String, var preferences: List[Woman] = List()) {
8+
def propose(): Unit = preferences match {
9+
case woman :: remainingPreferences => {
10+
if (woman.prefers(this)) {
11+
bachelors ++= woman.fiance
12+
woman.fiance = Some(this)
13+
}
14+
else
15+
bachelors.enqueue(this)
16+
preferences = remainingPreferences
17+
}
18+
case _ =>
19+
}
20+
}
21+
22+
case class Woman(name: String, var preferences: List[Man] = List(), var fiance: Option[Man] = None) {
23+
def prefers(man: Man): Boolean =
24+
fiance match {
25+
case Some(otherMan) => preferences.indexOf(man) < preferences.indexOf(otherMan)
26+
case _ => true //always prefer any man over nobody
27+
}
28+
}
29+
30+
def findStableMatches(men: Man*): Unit = {
31+
bachelors = men.to[Queue]
32+
while (bachelors.nonEmpty)
33+
bachelors.dequeue.propose()
34+
}
35+
}
36+
37+
object StableMarriageExample {
38+
39+
val a = StableMarriage.Man("Adam")
40+
val b = StableMarriage.Man("Bart")
41+
val c = StableMarriage.Man("Colm")
42+
val x = StableMarriage.Woman("Xena")
43+
val y = StableMarriage.Woman("Yeva")
44+
val z = StableMarriage.Woman("Zara")
45+
46+
a.preferences = List(y, x, z)
47+
b.preferences = List(y, z, x)
48+
c.preferences = List(x, z, y)
49+
x.preferences = List(b, a, c)
50+
y.preferences = List(c, a, b)
51+
z.preferences = List(a, c, b)
52+
53+
54+
def main(args: Array[String]): Unit = {
55+
56+
StableMarriage.findStableMatches(a, b, c)
57+
58+
List(x, y, z).foreach(
59+
w => Console.println(
60+
w.name
61+
+ " is married to "
62+
+ w.fiance.getOrElse(StableMarriage.Man("Nobody")).name))
63+
}
64+
65+
}

Diff for: contents/stable_marriage_problem/stable_marriage_problem.md

+2
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ I am incredibly interested to see what you guys do and how you implement the alg
4646
[import, lang:"java"](code/java/stable-marriage.java)
4747
{% sample lang="php" %}
4848
[import, lang:"php"](code/php/stable_marriage.php)
49+
{% sample lang="scala" %}
50+
[import, lang:"scala"](code/scala/stable_marriage.scala)
4951
{% endmethod %}
5052

5153
<script>

0 commit comments

Comments
 (0)