一个泛型方法,可以返回两个参数之间的随机整数,就像ruby对rand(0..n)所做的那样。
任何建议吗?
一个泛型方法,可以返回两个参数之间的随机整数,就像ruby对rand(0..n)所做的那样。
任何建议吗?
当前回答
下面是Kotlin中的一个简单的解决方案,它也适用于KMM:
fun IntRange.rand(): Int =
Random(Clock.System.now().toEpochMilliseconds()).nextInt(first, last)
对于每次运行的不同随机数需要Seed。您也可以为LongRange做同样的事情。
其他回答
实现s1m0nw1的答案的另一种方法是通过变量访问它。这并不是说它更有效率,而是它使你不必输入()。
val ClosedRange<Int>.random: Int
get() = Random().nextInt((endInclusive + 1) - start) + start
现在它可以被这样访问
(1..10).random
没有标准的方法可以做到这一点,但是您可以使用Math.random()或java.util.Random类轻松创建自己的方法。下面是一个使用Math.random()方法的例子:
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) })
}
这是一个示例输出:
[9, 8, 1, 7, 5, 6, 9, 8, 1, 9]
[5, 8, 9, 7, 6, 6, 8, 6, 7, 9]
不再需要使用自定义扩展函数。IntRange现在有一个即用的random()扩展函数。
val randomNumber = (0..10).random()
使用顶级函数,你可以实现与Ruby中完全相同的调用语法(如你所愿):
fun rand(s: Int, e: Int) = Random.nextInt(s, e + 1)
用法:
rand(1, 3) // returns either 1, 2 or 3
成为超级高手))
fun rnd_int(min: Int, max: Int): Int {
var max = max
max -= min
return (Math.random() * ++max).toInt() + min
}