Skip to content

Instantly share code, notes, and snippets.

@ThiporKong
ThiporKong / tsort.scala
Last active October 5, 2020 21:35
Topological sorting: simple implementation in pure Scala
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)
}
@ashee
ashee / cycle.scala
Created November 1, 2012 20:41
scala equivalent of haskell's cycle
// 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)
@jesperdj
jesperdj / MersenneTwister.scala
Created March 25, 2011 22:28
Mersenne Twister - Random number generator
// 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