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

任何建议吗?


当前回答

基于@s1m0nw1的优秀答案,我做了以下更改。

(0..n)在Kotlin中表示包含 (0到n)在Kotlin中表示独占 为Random实例使用单例对象(可选)

代码:

private object RandomRangeSingleton : Random()

fun ClosedRange<Int>.random() = RandomRangeSingleton.nextInt((endInclusive + 1) - start) + start

测试用例:

fun testRandom() {
        Assert.assertTrue(
                (0..1000).all {
                    (0..5).contains((0..5).random())
                }
        )
        Assert.assertTrue(
                (0..1000).all {
                    (0..4).contains((0 until 5).random())
                }
        )
        Assert.assertFalse(
                (0..1000).all {
                    (0..4).contains((0..5).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()

如果要从中选择的数字不是连续的,则可以使用random()。

用法:

val list = listOf(3, 1, 4, 5)
val number = list.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

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

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

或者使用Java Random

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

基于@s1m0nw1的优秀答案,我做了以下更改。

(0..n)在Kotlin中表示包含 (0到n)在Kotlin中表示独占 为Random实例使用单例对象(可选)

代码:

private object RandomRangeSingleton : Random()

fun ClosedRange<Int>.random() = RandomRangeSingleton.nextInt((endInclusive + 1) - start) + start

测试用例:

fun testRandom() {
        Assert.assertTrue(
                (0..1000).all {
                    (0..5).contains((0..5).random())
                }
        )
        Assert.assertTrue(
                (0..1000).all {
                    (0..4).contains((0 until 5).random())
                }
        )
        Assert.assertFalse(
                (0..1000).all {
                    (0..4).contains((0..5).random())
                }
        )
    }