Random numbers

suggest change

Kotlin has a multiplatform random number API in the kotlin.random package. It works the same on Kotlin/JVM, Kotlin/JS and Kotlin/Native, and the collection and range helpers (random(), shuffled()) are built on it.

On the JVM you can also use Java's generators: java.util.Random, ThreadLocalRandom, SplittableRandom, the Java 17 RandomGenerator API and SecureRandom. Kotlin converts between the two worlds with asJavaRandom() and asKotlinRandom().

This article covers:

The examples print random values, so your output will differ. Where that matters the output block says "possible output".

The basics: Random.Default

Random is an abstract class. Its companion object, Random.Default, is a ready-to-use generator, and because the companion has the same name as the class, you call it simply as Random.nextInt():

import kotlin.random.Random

fun main() {
    println(Random.nextInt())          // any Int, including negative ones
    println(Random.nextInt(10))        // 0..9    (upper bound is exclusive)
    println(Random.nextInt(1, 7))      // 1..6    (from inclusive, until exclusive)
    println(Random.nextLong(1_000_000_000_000))
    println(Random.nextDouble())       // 0.0 <= x < 1.0
    println(Random.nextDouble(5.0, 10.0))
    println(Random.nextFloat())        // 0.0f <= x < 1.0f
    println(Random.nextBoolean())
}

Possible output:

-1394625031
7
4
482915733112
0.6237049021633581
8.902176412290534
0.13894027
true

The bounds follow the usual half-open convention: nextInt(from, until) can return from but never until. If the range is empty (until <= from), the call throws IllegalArgumentException.

Inclusive ranges

Ranges are easier to read when both ends are included, as with a die. Use the nextInt(IntRange) extension (it must be imported) or call random() on the range itself:

import kotlin.random.Random
import kotlin.random.nextInt
import kotlin.random.nextLong

fun main() {
    val die1 = Random.nextInt(1..6)          // 1 to 6, both included
    val die2 = (1..6).random()               // same thing, no imports needed
    val big = Random.nextLong(1L..100L)
    val letter = ('a'..'z').random()

    println("$die1 $die2 $big $letter")
}

Possible output:

3 6 42 q

IntRange.random(), LongRange.random() and CharRange.random() live in kotlin.ranges, which is imported by default. An empty range such as (5..1).random() throws NoSuchElementException.

Unsigned numbers and bytes

import kotlin.random.Random
import kotlin.random.nextUInt
import kotlin.random.nextULong

fun main() {
    println(Random.nextUInt())                // 0 .. 4294967295
    println(Random.nextULong())
    println(Random.nextUInt(100u))            // 0u .. 99u

    val bytes = Random.nextBytes(8)           // new ByteArray of size 8
    println(bytes.joinToString(" ") { "%02x".format(it) })

    val buffer = ByteArray(4)
    Random.nextBytes(buffer)                  // fill an existing array
    println(buffer.toList())
}

Possible output:

3204729876
11829412376251390977
57
9f 03 c4 7a 11 e8 5d 20
[-23, 101, 7, -88]

nextBytes from kotlin.random is not suitable for keys or tokens. See "Secure random values" below.

Random elements and shuffling

Collections, arrays and ranges have random(), randomOrNull(), shuffled() and (for mutable lists and arrays) shuffle():

enum class Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

fun main() {
    val colors = listOf("red", "green", "blue")
    println(colors.random())

    println(Suit.entries.random())

    val empty = emptyList<String>()
    println(empty.randomOrNull())           // null instead of an exception

    val numbers = (1..10).toList()
    println(numbers.shuffled())             // new list, original unchanged
    println(numbers)

    val deck = mutableListOf("A", "K", "Q", "J", "10")
    deck.shuffle()                          // shuffles in place
    println(deck)

    val arr = intArrayOf(1, 2, 3, 4, 5)
    arr.shuffle()
    println(arr.contentToString())
}

Possible output:

blue
HEARTS
null
[7, 2, 10, 5, 1, 9, 4, 3, 8, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[Q, 10, A, J, K]
[4, 1, 5, 3, 2]

random() on an empty collection throws NoSuchElementException, so use randomOrNull() when the collection may be empty. Shuffling uses the Fisher-Yates algorithm, so every permutation is equally likely.

Sampling without replacement

To pick k distinct elements, shuffle and take the first k:

fun main() {
    val players = listOf("Ann", "Bob", "Cid", "Dee", "Eve", "Fay")
    val team = players.shuffled().take(3)
    println(team)

    // 6 distinct lottery numbers from 1..49, sorted for display
    val lotto = (1..49).shuffled().take(6).sorted()
    println(lotto)
}

Possible output:

[Eve, Ann, Dee]
[3, 11, 19, 27, 38, 44]

For very large inputs where you need only a few elements, shuffling everything is wasteful. Picking random indexes into a set until you have enough is cheaper:

import kotlin.random.Random

fun <T> List<T>.sample(k: Int, random: Random = Random): List<T> {
    require(k in 0..size) { "k must be in 0..$size" }
    val picked = LinkedHashSet<Int>()
    while (picked.size < k) picked += random.nextInt(size)
    return picked.map { this[it] }
}

fun main() {
    val ids = List(1_000_000) { it }
    println(ids.sample(5))
}

Possible output:

[318842, 77125, 905310, 412, 660017]

This is efficient when k is much smaller than size. When k gets close to size, use shuffled().take(k).

Seeded generators: reproducible randomness

Random(seed) creates a generator whose sequence is fully determined by the seed. Two generators with the same seed produce the same values:

import kotlin.random.Random

fun main() {
    val a = Random(42)
    val b = Random(42)

    val first = List(5) { a.nextInt(100) }
    val second = List(5) { b.nextInt(100) }

    println(first == second)
    println(List(5) { Random(7).nextInt(100) }.distinct().size)
}
true
1

The second line shows a common bug: creating a new generator with the same seed for every value returns the same number every time. Create the seeded generator once and reuse it.

Seeds are useful for:

import kotlin.random.Random

fun main(args: Array<String>) {
    val seed = args.firstOrNull()?.toLong() ?: System.nanoTime()
    println("seed = $seed")   // print it so a failing run can be repeated
    val rnd = Random(seed)

    val data = List(10) { rnd.nextInt(1000) }
    println(data)
}

Kotlin documents that the same seed gives the same sequence within the same version of the Kotlin runtime; the algorithm may change in a future release. If you persist seeds long term (for example saved game worlds), java.util.Random(seed) is the safer choice on the JVM, because its algorithm is fixed by the Java specification.

Random(seed) is also shared state: the generator is not synchronized, so don't use one seeded instance from several threads at once.

Making random code testable

Code that calls Random.nextInt() directly is hard to test, because the result changes on every run. Take a Random parameter instead and default it to Random:

import kotlin.random.Random

class Dice(private val random: Random = Random) {
    fun roll(): Int = random.nextInt(1, 7)
    fun rollMany(n: Int): List<Int> = List(n) { roll() }
}

fun main() {
    val production = Dice()                 // truly random
    println(production.rollMany(5))

    val t1 = Dice(Random(123)).rollMany(5)  // reproducible in tests
    val t2 = Dice(Random(123)).rollMany(5)
    println(t1 == t2)
}

Possible output:

[2, 6, 1, 1, 4]
true

For full control you can subclass Random. Only nextBits is abstract; everything else is derived from it, though you can override other methods too:

import kotlin.random.Random

// Always returns the given values in order, for deterministic tests.
class FixedRandom(vararg values: Int) : Random() {
    private val queue = ArrayDeque(values.toList())
    override fun nextBits(bitCount: Int): Int = error("not used")
    override fun nextInt(from: Int, until: Int): Int = queue.removeFirst()
}

fun main() {
    val dice = Dice(FixedRandom(6, 6, 1))
    println(dice.rollMany(3))
}

class Dice(private val random: Random = Random) {
    fun roll(): Int = random.nextInt(1, 7)
    fun rollMany(n: Int): List<Int> = List(n) { roll() }
}
[6, 6, 1]

Weighted random choice

random() gives each element the same chance. For different probabilities, pick a number in [0, totalWeight) and walk the cumulative weights:

import kotlin.random.Random

fun <T> weightedRandom(items: Map<T, Double>, random: Random = Random): T {
    require(items.isNotEmpty() && items.values.all { it >= 0.0 })
    val total = items.values.sum()
    var r = random.nextDouble(total)
    for ((item, weight) in items) {
        r -= weight
        if (r < 0) return item
    }
    return items.keys.last() // guards against floating-point rounding
}

fun main() {
    val loot = mapOf("common" to 70.0, "rare" to 25.0, "legendary" to 5.0)

    val counts = List(100_000) { weightedRandom(loot) }
        .groupingBy { it }
        .eachCount()
    println(counts)
}

Possible output:

{common=70081, rare=24935, legendary=4984}

The linear scan is fine for a handful of items. For thousands of items and many draws, precompute the cumulative array once and use binary search:

import kotlin.random.Random

class WeightedPicker<T>(items: List<Pair<T, Double>>, private val random: Random = Random) {
    private val values = items.map { it.first }
    private val cumulative = items.runningFold(0.0) { acc, (_, w) -> acc + w }.drop(1).toDoubleArray()

    fun next(): T {
        val r = random.nextDouble(cumulative.last())
        val i = cumulative.binarySearch(r)
        // binarySearch returns -(insertionPoint) - 1 when r is not found exactly
        val index = if (i >= 0) i + 1 else -i - 1
        return values[index]
    }
}

fun main() {
    val picker = WeightedPicker(listOf("a" to 1.0, "b" to 2.0, "c" to 7.0))
    println(List(20) { picker.next() }.joinToString(""))
}

Possible output:

ccbcccacccbccccbcacc

Normal (Gaussian) distribution

kotlin.random.Random produces uniformly distributed numbers. For a bell curve on the JVM use nextGaussian(). Since Java 17 it also accepts a mean and a standard deviation:

import java.util.concurrent.ThreadLocalRandom

fun main() {
    val rnd = ThreadLocalRandom.current()
    val iqScores = List(10) { rnd.nextGaussian(100.0, 15.0).toInt() }
    println(iqScores)
}

Possible output:

[112, 94, 101, 87, 123, 99, 105, 78, 108, 96]

To get a Gaussian from a Kotlin Random (for example a seeded one), wrap it with asJavaRandom(). In common (multiplatform) code, use the Box-Muller transform:

import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.ln
import kotlin.math.sqrt
import kotlin.random.Random
import kotlin.random.asJavaRandom

fun Random.nextGaussian(mean: Double = 0.0, stdDev: Double = 1.0): Double {
    val u1 = 1.0 - nextDouble()   // (0, 1], avoids ln(0)
    val u2 = nextDouble()
    val z = sqrt(-2.0 * ln(u1)) * cos(2.0 * PI * u2)
    return mean + z * stdDev
}

fun main() {
    val seeded = Random(2024)
    println(seeded.asJavaRandom().nextGaussian())    // JVM only

    val samples = List(100_000) { Random.nextGaussian(50.0, 10.0) }
    val mean = samples.average()
    val sd = sqrt(samples.sumOf { (it - mean) * (it - mean) } / samples.size)
    println("mean=%.2f sd=%.2f".format(mean, sd))
}

Possible output:

0.048350983897349445
mean=50.01 sd=9.98

Monte Carlo example: estimating pi

Random sampling can approximate values that are hard to compute directly. Throw random points into the unit square; the fraction that lands inside the quarter circle approaches pi/4:

import kotlin.random.Random

fun estimatePi(samples: Int, random: Random = Random): Double {
    var inside = 0
    repeat(samples) {
        val x = random.nextDouble()
        val y = random.nextDouble()
        if (x * x + y * y <= 1.0) inside++
    }
    return 4.0 * inside / samples
}

fun main() {
    for (n in listOf(1_000, 100_000, 10_000_000)) {
        println("%,12d -> %.5f".format(n, estimatePi(n)))
    }
}

Possible output:

       1,000 -> 3.18000
     100,000 -> 3.14240
  10,000,000 -> 3.14146

The error shrinks proportionally to 1/sqrt(n), so every extra digit costs about 100 times more samples.

Thread safety and Java generators

Generator Thread-safe? Notes
kotlin.random.Random (default) yes on the JVM it delegates to ThreadLocalRandom
kotlin.random.Random(seed) no one instance per thread or coroutine
java.util.Random yes synchronized with atomics, slows down under contention
ThreadLocalRandom.current() per thread fast; always call current() in the thread that uses it
SplittableRandom no split() gives independent generators for parallel tasks
java.security.SecureRandom yes for security; slower

For most code Random (Kotlin's default) is the right choice: it is fast and safe to call from any thread or coroutine.

Java 17 added the java.util.random.RandomGenerator interface and a set of modern algorithms (LXM family, Xoshiro) you can select by name:

import java.util.random.RandomGenerator
import java.util.random.RandomGeneratorFactory

fun main() {
    val gen = RandomGenerator.of("L64X128MixRandom")
    println(gen.nextInt(1, 7))
    println(gen.nextDouble())

    RandomGeneratorFactory.all()
        .map { it.name() }
        .sorted()
        .forEach { println(it) }
}

Possible output (the list depends on the JDK):

5
0.4170303102368742
L128X1024MixRandom
L128X128MixRandom
L128X256MixRandom
L32X64MixRandom
L64X1024MixRandom
L64X128MixRandom
L64X128StarStarRandom
L64X256MixRandom
Random
SecureRandom
SplittableRandom
Xoroshiro128PlusPlus
Xoshiro256PlusPlus

Converting between Kotlin and Java generators

Use asKotlinRandom() to use a Java generator with Kotlin APIs such as shuffled(random), and asJavaRandom() to pass a Kotlin generator to a Java API:

import java.util.concurrent.ThreadLocalRandom
import kotlin.random.Random
import kotlin.random.asJavaRandom
import kotlin.random.asKotlinRandom

fun main() {
    val kotlinRnd: Random = ThreadLocalRandom.current().asKotlinRandom()
    println((1..5).shuffled(kotlinRnd))

    val javaRnd: java.util.Random = Random(1).asJavaRandom()
    println(javaRnd.ints(3, 0, 10).toArray().toList())
}

Possible output:

[4, 1, 5, 2, 3]
[5, 6, 2]

Secure random values

kotlin.random.Random, java.util.Random, ThreadLocalRandom and the RandomGenerator algorithms are pseudo-random: given a few outputs, an attacker can often predict the next ones. For session ids, password reset tokens, API keys, salts and generated passwords, use java.security.SecureRandom.

Because SecureRandom extends java.util.Random, asKotlinRandom() lets you use it with all the Kotlin helpers:

import java.security.SecureRandom
import java.util.Base64
import kotlin.random.asKotlinRandom

private val secure = SecureRandom().asKotlinRandom()

private const val ALPHABET =
    "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#%&*"

fun generatePassword(length: Int = 16): String =
    (1..length).map { ALPHABET.random(secure) }.joinToString("")

fun generateToken(bytes: Int = 32): String =
    Base64.getUrlEncoder().withoutPadding().encodeToString(secure.nextBytes(bytes))

fun main() {
    println(generatePassword())
    println(generateToken())
}

Possible output:

q7#Tn2bWk!xHe9Rz
3vC0bS1nT6m0qJ9oZbFq1yQ2u3o0b8lCk8c3xL9pZ2Y

String.random(random) works because String is a CharSequence. More on keys and hashing is in Cryptography.

For unique identifiers that don't need to be secret, java.util.UUID.randomUUID() is simpler. It is also generated with SecureRandom:

import java.util.UUID

fun main() {
    println(UUID.randomUUID())
}

Possible output:

1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed

Common mistakes

Off-by-one in the upper bound. Random.nextInt(1, 6) returns 1..5, never 6. Use nextInt(1, 7), Random.nextInt(1..6) or (1..6).random().

Using abs() and % to limit the range. This is biased, and it can even return a negative number:

import kotlin.math.absoluteValue

fun main() {
    val bad = Int.MIN_VALUE.absoluteValue % 6   // what Random.nextInt().absoluteValue % 6 can produce
    println(bad)
}
-2

Int.MIN_VALUE has no positive counterpart, so its absolute value is itself. nextInt(until) handles bounds correctly and without bias.

Re-creating a seeded generator in a loop. Random(seed).nextInt() in a loop returns the same value on every iteration. Seeding with System.currentTimeMillis() in a loop is no better: calls in the same millisecond get the same seed. Create the generator once.

Expecting nextDouble() to return 1.0. nextDouble() returns values in [0.0, 1.0). For integers where the upper bound must be included, use an inclusive IntRange.

Sharing a seeded Random across threads. Random(seed) has unsynchronized mutable state. Give each thread or coroutine its own instance, for example Random(baseSeed + workerIndex).

Using Random for secrets. Tokens, passwords and keys must come from SecureRandom.

Summary

Task Code
random Int in [0, n) Random.nextInt(n)
random Int in [a, b] (a..b).random() or Random.nextInt(a..b)
random Double in [0, 1) Random.nextDouble()
random element list.random(), list.randomOrNull()
shuffle list.shuffled(), mutableList.shuffle()
k distinct elements list.shuffled().take(k)
reproducible sequence Random(seed) created once
Gaussian ThreadLocalRandom.current().nextGaussian(mean, sd)
secure token SecureRandom().asKotlinRandom().nextBytes(n)
unique id UUID.randomUUID()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents