Groovy: Random numbers, random selection from list of values
In order to generate pseudo-random numbers in Groovy, we can use the Math.random() method or the Random class provided by Java.
Random float
The random method will generate a floating point number between 0 and 1. (0 included 1 excluded).
examples/groovy/random_float.gvy
println(Math.random())
Random integers
examples/groovy/random_integers.gvy
Random rnd = new Random() println(rnd.next(2)) // 2 bits of random number that is, one of the following: 0,1,2,3 println(rnd.nextInt(3)) // random integer in the range of 0, 3 (so one of 0,1, 2)
In the next example we have a list of one-letter strings and we would like to pick one of the elements randomly. So we need an integer between 0 and the size of the array.
We run it in a loop so we can see more values picked.
examples/groovy/random_selection.gvy
def z = ["a", "b", "c", "d", "e"] Random rnd = new Random() for (i=0; i < 10; i++) { println(z[rnd.nextInt(z.size)]) }
Published on 2018-09-14