Reputation: 109
How do you create random seeded arrays in Scala? I would want to have a random array but this random array must be the same all through out the function.
Using scala.util
, we can do, for example
val arr1 = Array.fill[Float](Random.nextFloat)
However, arr1
changes every time the process goes through it.
Since we also have seeds in Scala, I've tried doing:
val rndm = Random(4)
val arr1 = Array.fill[Float](rndm.nextFloat)
Still, it changes every time even if there is a seed.
Upvotes: 0
Views: 158
Reputation: 20415
Create a random generator with a seed,
val r = new scala.util.Random(100)
To re-create the same sequence of pseudo-random values you need to "reset" the generator, otherwise it will add new (possibly) different values to the next sequences,
scala> val r = new scala.util.Random(100)
r: scala.util.Random = scala.util.Random@5b1dd206
scala> Array.fill(2)(r.nextFloat)
res6: Array[Float] = Array(0.7220096, 0.7346627)
scala> val r = new scala.util.Random(100)
r: scala.util.Random = scala.util.Random@6f371390
scala> Array.fill(2)(r.nextFloat)
res7: Array[Float] = Array(0.7220096, 0.7346627)
Upvotes: 2