Last active
October 5, 2020 21:35
-
-
Save ThiporKong/4399695 to your computer and use it in GitHub Desktop.
Topological sorting: simple implementation in pure 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[A](edges: Traversable[(A, A)]): Iterable[A] = { | |
@tailrec | |
def tsort(toPreds: Map[A, Set[A]], done: Iterable[A]): Iterable[A] = { | |
val (noPreds, hasPreds) = toPreds.partition { _._2.isEmpty } | |
if (noPreds.isEmpty) { | |
if (hasPreds.isEmpty) done else sys.error(hasPreds.toString) | |
} else { | |
val found = noPreds.map { _._1 } | |
tsort(hasPreds.mapValues { _ -- found }, done ++ found) | |
} | |
} | |
val toPred = edges.foldLeft(Map[A, Set[A]]()) { (acc, e) => | |
acc + (e._1 -> acc.getOrElse(e._1, Set())) + (e._2 -> (acc.getOrElse(e._2, Set()) + e._1)) | |
} | |
tsort(toPred, Seq()) | |
} | |
println(tsort(Seq((1, 2), (2, 4), (3, 4), (3, 2), (1,3)))) |
this was useful, thanks. +1 to @infomarte's comment
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would you mind to make this nice piece of code available under some permissive licence (like MIT or BSD) such that it can be used in open-source projects?