This file contains hidden or 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) | |
} |
This file contains hidden or 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
// cycle will lazily cycle through values from the seq argument | |
def cycle[T](seq: Seq[T]) = Stream.continually(seq).flatten | |
scala> val c = cycle(List(1, 2, 3)) | |
scala> c take 10 force | |
res24: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 1, 2, 3, 1, 2, 3, 1) | |
This file contains hidden or 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
// Mersenne Twister 19937 | |
// Based on code from: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html | |
// Note: This implementation is not thread-safe! | |
final class MersenneTwister (seed: Int = 5489) { | |
private val N = 624 | |
private val M = 397 | |
private val MatrixA = 0x9908b0dfL | |
private val UpperMask = 0x80000000L |