Created
September 21, 2015 19:18
-
-
Save kirked/4552e4d3c932d99bcb9f to your computer and use it in GitHub Desktop.
Generator for test data
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
import scala.util.Random | |
trait Generator[A] extends Function0[A] { | |
val random = new Random | |
def apply: A | |
} | |
object Generator { | |
def of[A](as: A*): Generator[A] = { | |
new Generator[A] { | |
def apply: A = { | |
val next = random.nextInt(as.length) | |
as(next) | |
} | |
} | |
} | |
def withProbability[A](as: (A, Double)*): Generator[A] = { | |
new Generator[A] { | |
val normals = { | |
val total = as.foldLeft(0.0) { case (acc, (tuple)) => acc + tuple._2 } | |
var runningTotal = 0.0 | |
as.map { tuple => | |
runningTotal += tuple._2 | |
(runningTotal / total, tuple._1) | |
} | |
} | |
def apply: A = { | |
val value = random.nextDouble | |
normals.dropWhile(value > _._1).head._2 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment