Stable marriage problem: Difference between revisions
Content added Content deleted
(→{{header|Scala}}: unused import removal) |
(→{{header|Scala}}: update) |
||
Line 5,655: | Line 5,655: | ||
{{trans|Java}} |
{{trans|Java}} |
||
<lang scala>object SMP extends App { |
<lang scala>object SMP extends App { |
||
def |
private def checkMarriages(): Unit = |
||
if (check) |
|||
⚫ | |||
if (checkMatches(matches)) |
|||
println("Marriages are stable") |
println("Marriages are stable") |
||
else |
else |
||
println("Marriages are unstable") |
println("Marriages are unstable") |
||
private def swap() { |
|||
val girl1 = girls.head |
val girl1 = girls.head |
||
val girl2 = girls(1) |
val girl2 = girls(1) |
||
val tmp = matches(girl1) |
val tmp = girl2 -> matches(girl1) |
||
matches += girl1 -> matches(girl2) |
matches += girl1 -> matches(girl2) |
||
matches += |
matches += tmp |
||
println(girl1 + " and " + girl2 + " have switched partners") |
println(girl1 + " and " + girl2 + " have switched partners") |
||
if (checkMatches(matches)) |
|||
println("Marriages are stable") |
|||
⚫ | |||
println("Marriages are unstable") |
|||
} |
} |
||
private type TM = scala.collection.mutable.TreeMap[String, String] |
private type TM = scala.collection.mutable.TreeMap[String, String] |
||
private def |
private def check: Boolean = { |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
private def checkMatches(matches: scala.collection.Map[String, String]): Boolean = { |
|||
if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet)) |
if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet)) |
||
return false |
return false |
||
val invertedMatches = new TM |
val invertedMatches = new TM |
||
matches |
matches foreach { invertedMatches += _.swap } |
||
for ((k, v) <- matches) { |
for ((k, v) <- matches) { |
||
Line 5,760: | Line 5,728: | ||
"ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"), |
"ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"), |
||
"jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan")) |
"jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan")) |
||
⚫ | |||
private lazy val matches = { |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
checkMarriages() |
|||
⚫ | |||
checkMarriages() |
|||
}</lang> |
}</lang> |
||
{{out}} |
{{out}} |