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

任何建议吗?


当前回答

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

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

其他回答

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

在Kotlin SDK >=1.3中,你可以这样做

import kotlin.random.Random

val number = Random.nextInt(limit)

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

用法:

val list = listOf(3, 1, 4, 5)
val number = list.random()

返回列表中的一个数字。

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

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

用法:

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

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

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

或者使用Java Random

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