W3cubDocs

/Kotlin

Random

Platform and version requirements: JVM (1.3), JS (1.3), Native (1.3)
fun Random(seed: Int): Random

Returns a repeatable random number generator seeded with the given seed Int value.

Two generators with the same seed produce the same sequence of values within the same version of Kotlin runtime.

Note: Future versions of Kotlin may change the algorithm of this seeded number generator so that it will return a sequence of values different from the current one for a given seed.

On JVM the returned generator is NOT thread-safe. Do not invoke it from multiple threads without proper synchronization.

import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
fun getRandomList(random: Random): List<Int> =
    List(10) { random.nextInt(0, 100) }

val randomValues1 = getRandomList(Random(42))
// prints the same sequence every time
println(randomValues1) // [33, 40, 41, 2, 41, 32, 21, 40, 69, 87]

val randomValues2 = getRandomList(Random(42))
// random with the same seed produce the same sequence
println("randomValues1 == randomValues2 is ${randomValues1 == randomValues2}") // true

val randomValues3 = getRandomList(Random(0))
// random with another seed produce another sequence
println(randomValues3) // [14, 48, 57, 67, 82, 7, 61, 27, 14, 59]
//sampleEnd
}
Platform and version requirements: JVM (1.3), JS (1.3), Native (1.3)
fun Random(seed: Long): Random

Returns a repeatable random number generator seeded with the given seed Long value.

Two generators with the same seed produce the same sequence of values within the same version of Kotlin runtime.

Note: Future versions of Kotlin may change the algorithm of this seeded number generator so that it will return a sequence of values different from the current one for a given seed.

On JVM the returned generator is NOT thread-safe. Do not invoke it from multiple threads without proper synchronization.

import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
fun getRandomList(random: Random): List<Int> =
    List(10) { random.nextInt(0, 100) }

val randomValues1 = getRandomList(Random(42))
// prints the same sequence every time
println(randomValues1) // [33, 40, 41, 2, 41, 32, 21, 40, 69, 87]

val randomValues2 = getRandomList(Random(42))
// random with the same seed produce the same sequence
println("randomValues1 == randomValues2 is ${randomValues1 == randomValues2}") // true

val randomValues3 = getRandomList(Random(0))
// random with another seed produce another sequence
println(randomValues3) // [14, 48, 57, 67, 82, 7, 61, 27, 14, 59]
//sampleEnd
}

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.random/-random.html