5
How can I get a random number between two values? Like ruby does with rand(0..n)
5
How can I get a random number between two values? Like ruby does with rand(0..n)
6
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 as follows:
(0..10).random() // => retorná um númeor entre 0 e 9 (incluso)
Source: https://stackoverflow.com/questions/45685026/how-can-i-get-a-random-number-in-kotlin
Browser other questions tagged java random kotlin random-numbers
You are not signed in. Login or sign up in order to post.
I found this method by extensive functions very intriguing. Very good to know more and more of Kotlin just in reading answers
– Jefferson Quesado