Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.ThreadLocalRandom
- import scala.concurrent.ExecutionContext.Implicits.global
- import scala.concurrent.{Await, Future}
- import scala.concurrent.duration._
- sealed trait RandomOps {
- def randomInteger(lo: Int, hi: Int): Future[Int]
- }
- class PseudoRandom extends RandomOps {
- override def randomInteger(lo: Int, hi: Int): Future[Int] = {
- Future.successful(ThreadLocalRandom.current().nextInt(lo, hi + 1))
- }
- }
- object PlayAround {
- // random number generator
- lazy val rng = new PseudoRandom
- // recursively create random slices
- private def recRandomSlices(add: Int, numSlice: Int, acc: Seq[Int]): Future[Seq[Int]] = {
- if (numSlice == 0) Future.successful(acc);
- else {
- val randValF = rng.randomInteger(0, add)
- randValF.transform(randVal => {
- if (numSlice == 1)
- recRandomSlices(0, 0, add +: acc)
- else
- recRandomSlices(add - randVal, numSlice - 1, randVal +: acc)
- } , t => t) flatMap identity
- }
- }
- // Returns the random number of slices
- def randomSlices(add: Int, numSlice: Int): Future[Seq[Int]] = {
- recRandomSlices(add, numSlice, Nil)
- }
- }
- object Slice {
- import PlayAround._
- def main(args: Array[String]) = {
- val seq = Await.result(randomSlices(15, 3), 30.seconds)
- println(seq)
- }
- }
Add Comment
Please, Sign In to add comment