一个泛型方法,可以返回两个参数之间的随机整数,就像ruby对rand(0..n)所做的那样。

任何建议吗?


当前回答

下面是Kotlin中的一个简单的解决方案,它也适用于KMM:

fun IntRange.rand(): Int =
    Random(Clock.System.now().toEpochMilliseconds()).nextInt(first, last)

对于每次运行的不同随机数需要Seed。您也可以为LongRange做同样的事情。

其他回答

我的建议是在IntRange上创建一个扩展函数,像这样创建随机(0..10).random()

TL;DR Kotlin >= 1.3,一个随机的所有平台

在1.3版本中,Kotlin自带多平台随机生成器。在KEEP中有描述。下面描述的扩展现在是Kotlin标准库的一部分,简单地像这样使用它:

val rnds = (0..10).random() // generated random from 0 to 10 included

在1.3之前,在JVM上我们使用Random,如果我们在JDK > 1.6上,我们甚至使用ThreadLocalRandom。

fun IntRange.random() = 
       Random().nextInt((endInclusive + 1) - start) + start

这样用:

// will return an `Int` between 0 and 10 (incl.)
(0..10).random()

如果你想让函数只返回1,2,…, 9(不包括10),使用until构造的范围:

(0 until 10).random()

如果您使用的是JDK > 1.6,请使用ThreadLocalRandom.current()而不是Random()。

KotlinJs和其他变体

对于kotlinjs和其他不允许使用java.util的用例。随机的,看这个选项。

另外,看看我的建议的变化。它还包括一个用于随机字符的扩展函数。

在[1,10]范围内的随机示例

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

或者使用Java Random

val random2 = Random().nextInt(10) + 1

Kotlin中的以下内容对我来说效果很好:

(fromNumber.rangeTo(toNumber)).random()

数字的范围以变量fromNumber开始,以变量toNumber结束。fromNumber和toNumber也将包含在由此生成的随机数中。

要在Kotlin中获得一个随机Int数,请使用以下方法:

import java.util.concurrent.ThreadLocalRandom

fun randomInt(rangeFirstNum:Int, rangeLastNum:Int) {
    val randomInteger = ThreadLocalRandom.current().nextInt(rangeFirstNum,rangeLastNum)
    println(randomInteger)
}
fun main() {    
    randomInt(1,10)
}


// Result – random Int numbers from 1 to 9

希望这能有所帮助。

使用顶级函数,你可以实现与Ruby中完全相同的调用语法(如你所愿):

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

用法:

rand(1, 3) // returns either 1, 2 or 3