How can I get a random number in Kotlin?

2019-01-30 17:32发布

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

Any suggestion?

18条回答
霸刀☆藐视天下
2楼-- · 2019-01-30 17:34

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<Int, Int>) = random(pair.first, pair.second)

fun main(args: Array<String>) {
    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]
查看更多
倾城 Initia
3楼-- · 2019-01-30 17:37

Examples random in the range [1, 10]

val random1 = (0..10).shuffled().last()

or utilizing Java Random

val random2 = Random().nextInt(10) + 1
查看更多
一夜七次
4楼-- · 2019-01-30 17:37

Using a top-level function, you can achieve exactly the same call syntax as in Ruby (as you wish):

fun rand(s: Int, e: Int) = Random.nextInt(s, e + 1)

Usage:

rand(1, 3) // returns either 1, 2 or 3
查看更多
老娘就宠你
5楼-- · 2019-01-30 17:37

In Kotlin 1.3 you can do it like

val number = Random.nextInt(limit)
查看更多
叼着烟拽天下
6楼-- · 2019-01-30 17:38

First, you need a RNG. In Kotlin you currently need to use the platform specific ones (there isn't a Kotlin built in one). For the JVM it's java.util.Random. You'll need to create an instance of it and then call random.nextInt(n).

查看更多
走好不送
7楼-- · 2019-01-30 17:39

As of kotlin 1.2, you could write:

(1..3).shuffled().last()

Just be aware it's big O(n), but for a small list (especially of unique values) it's alright :D

查看更多
登录 后发表回答