How can I get a random number between two values? As ruby does with rand(0..n)
How can I get a random number between two values? As ruby does with rand(0..n)
The first and most intuitive is to create a function that returns a random number using the class java.util.Random
:
import java.util.Random
val random = Random()
fun rand(from: Int, to: Int) : Int {
return random.nextInt(to - from) + from // from(incluso) e to(excluso)
}
Another more interesting way is to use extensive functions:
fun ClosedRange<Int>.random() =
Random().nextInt(endInclusive - start) + start
Soon after you can use it as follows:
(0..10).random() // => retorná um númeor entre 0 e 9 (incluso)
Source: link