Guest User

Untitled

a guest
Feb 24th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. import java.util.concurrent.ThreadLocalRandom
  2.  
  3. import scala.concurrent.ExecutionContext.Implicits.global
  4. import scala.concurrent.{Await, Future}
  5. import scala.concurrent.duration._
  6.  
  7. sealed trait RandomOps {
  8. def randomInteger(lo: Int, hi: Int): Future[Int]
  9. }
  10.  
  11. class PseudoRandom extends RandomOps {
  12. override def randomInteger(lo: Int, hi: Int): Future[Int] = {
  13. Future.successful(ThreadLocalRandom.current().nextInt(lo, hi + 1))
  14. }
  15. }
  16.  
  17. object PlayAround {
  18. // random number generator
  19. lazy val rng = new PseudoRandom
  20.  
  21. // recursively create random slices
  22. private def recRandomSlices(add: Int, numSlice: Int, acc: Seq[Int]): Future[Seq[Int]] = {
  23. if (numSlice == 0) Future.successful(acc);
  24. else {
  25. val randValF = rng.randomInteger(0, add)
  26. randValF.transform(randVal => {
  27. if (numSlice == 1)
  28. recRandomSlices(0, 0, add +: acc)
  29. else
  30. recRandomSlices(add - randVal, numSlice - 1, randVal +: acc)
  31. } , t => t) flatMap identity
  32. }
  33. }
  34.  
  35. // Returns the random number of slices
  36. def randomSlices(add: Int, numSlice: Int): Future[Seq[Int]] = {
  37. recRandomSlices(add, numSlice, Nil)
  38. }
  39. }
  40.  
  41. object Slice {
  42. import PlayAround._
  43.  
  44. def main(args: Array[String]) = {
  45. val seq = Await.result(randomSlices(15, 3), 30.seconds)
  46. println(seq)
  47. }
  48. }
Add Comment
Please, Sign In to add comment