Last active
December 15, 2015 17:49
-
-
Save chadselph/5299005 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* SCALA!! | |
*/ | |
object DisjointGraphs extends App { | |
val disjoints = findThem(List((1,2), (2,3), (5,6), (7,8), (1,8))) | |
println(disjoints) | |
def findThem(edges: List[(Int, Int)]) = { | |
val initial = List[Set[Int]]() // empty list of int sets | |
edges.foldLeft(initial)((sets, nextEdge) => | |
sets.partition(s => s(nextEdge._1) || s(nextEdge._2)) match { | |
case (Nil, rest) => Set(nextEdge._1, nextEdge._2) :: rest | |
case (List(s1, s2), rest) => s1.union(s2) :: rest | |
case (List(s1), rest) => s1 + nextEdge._1 + nextEdge._2 :: rest | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome use of foldLeft and partition !