A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n)
.
Any suggestion?
There is no standard method that does this but you can easily create your own using either Math.random()
or the class java.util.Random
. Here is an example using the Math.random()
method:
fun random(n: Int) = (Math.random() * n).toInt()
fun random(from: Int, to: Int) = (Math.random() * (to - from) + from).toInt()
fun random(pair: Pair) = random(pair.first, pair.second)
fun main(args: Array) {
val n = 10
val rand1 = random(n)
val rand2 = random(5, n)
val rand3 = random(5 to n)
println(List(10) { random(n) })
println(List(10) { random(5 to n) })
}
This is a sample output:
[9, 8, 1, 7, 5, 6, 9, 8, 1, 9]
[5, 8, 9, 7, 6, 6, 8, 6, 7, 9]