How can I get a random number in Kotlin?

后端 未结 22 1566
一个人的身影
一个人的身影 2020-12-12 15:02

A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n).

Any suggestion?

22条回答
  •  [愿得一人]
    2020-12-12 15:53

    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]
    

提交回复
热议问题