Created
July 30, 2013 11:04
-
-
Save bmarcot/6112036 to your computer and use it in GitHub Desktop.
Topological sort in Scala.
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
def tsort(gs: List[(Int, List[Int])]): List[Int] = { | |
gs match { | |
case g :: gs => { | |
if (g._2.isEmpty) g._1 :: tsort(gs.diff(List(g)).map(x => (x._1, x._2.diff(List(g._1))))) | |
else tsort(gs :+ g) | |
} | |
case _ => List() | |
} | |
} | |
println(tsort(List((1, List(3, 5)), (2, List(3)), (3, List(4, 5)), (4, List()), (5, List())))) | |
// List(4, 5, 3, 1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment