一个泛型方法,可以返回两个参数之间的随机整数,就像ruby对rand(0..n)所做的那样。
任何建议吗?
一个泛型方法,可以返回两个参数之间的随机整数,就像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
其他回答
你可以创建一个类似于java.util.Random.nextInt(int)的扩展函数,但它的边界是一个inrange而不是int:
fun Random.nextInt(range: IntRange): Int {
return range.start + nextInt(range.last - range.start)
}
你现在可以对任何随机实例使用这个:
val random = Random()
println(random.nextInt(5..9)) // prints 5, 6, 7, 8, or 9
如果你不想管理自己的随机实例,那么你可以定义一个方便的方法,例如使用ThreadLocalRandom.current():
fun rand(range: IntRange): Int {
return ThreadLocalRandom.current().nextInt(range)
}
现在你可以像在Ruby中一样获得一个随机整数,而不需要自己首先声明一个随机实例:
rand(5..9) // returns 5, 6, 7, 8, or 9
从随机数生成器获取下一个随机Int。
Random.nextInt()
在[1,10]范围内的随机示例
val random1 = (0..10).shuffled().last()
或者使用Java Random
val random2 = Random().nextInt(10) + 1
下面是Kotlin中的一个简单的解决方案,它也适用于KMM:
fun IntRange.rand(): Int =
Random(Clock.System.now().toEpochMilliseconds()).nextInt(first, last)
对于每次运行的不同随机数需要Seed。您也可以为LongRange做同样的事情。
要在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
希望这能有所帮助。