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

任何建议吗?


当前回答

没有标准的方法可以做到这一点,但是您可以使用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]

其他回答

在from(含)和to(不含)之间生成一个随机整数

import java.util.Random

val random = Random()

fun rand(from: Int, to: Int) : Int {
    return random.nextInt(to - from) + from
}

可能的变化,我的其他答案随机字符

为了获得随机字符,可以像这样定义一个扩展函数

fun ClosedRange<Char>.random(): Char = 
       (Random().nextInt(endInclusive.toInt() + 1 - start.toInt()) + start.toInt()).toChar()

// will return a `Char` between A and Z (incl.)
('A'..'Z').random()

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

对于kotlinjs和其他不允许使用java.util的用例。随机,这个答案会有帮助。

Kotlin >= 1.3多平台随机支持

在1.3版本中,Kotlin自带多平台随机生成器。在KEEP中有描述。你现在可以直接使用扩展作为Kotlin标准库的一部分,而不需要定义它:

('a'..'b').random()

Kotlin >= 1.3,多平台随机支持

从1.3开始,标准库就为随机提供了多平台支持。

JavaScript上的Kotlin < 1.3

如果您正在使用Kotlin JavaScript,并且无法访问java.util。随机,以下将工作:

fun IntRange.random() = (Math.random() * ((endInclusive + 1) - start) + start).toInt()

这样用:

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

你可以创建一个扩展函数:

infix fun ClosedRange<Float>.step(step: Float): Iterable<Float> {
    require(start.isFinite())
    require(endInclusive.isFinite())
    require(step.round() > 0.0) { "Step must be positive, was: $step." }
    require(start != endInclusive) { "Start and endInclusive must not be the same"}

    if (endInclusive > start) {
        return generateSequence(start) { previous ->
            if (previous == Float.POSITIVE_INFINITY) return@generateSequence null
            val next = previous + step.round()
            if (next > endInclusive) null else next.round()
        }.asIterable()
    }

    return generateSequence(start) { previous ->
        if (previous == Float.NEGATIVE_INFINITY) return@generateSequence null
        val next = previous - step.round()
        if (next < endInclusive) null else next.round()
    }.asIterable()
}

Round Float值:

fun Float.round(decimals: Int = DIGITS): Float {
    var multiplier = 1.0f
    repeat(decimals) { multiplier *= 10 }
    return round(this * multiplier) / multiplier
}

方法的用法:

(0.0f .. 1.0f).step(.1f).forEach { System.out.println("value: $it") }

输出:

取值:0.0值:0.1值:0.2值:0.3值:0.4值:0.5 取值:0.6值:0.7值:0.8值:0.9值:1.0

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

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

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