Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a random number in Kotlin?

Tags:

random

jvm

kotlin

People also ask

Is Kotlin random inclusive?

Kotlin offers the Random class in the kotlin. random package, which can generate random numbers. You can use its nextInt() function to get a pseudorandom integer value between 0 (inclusive) and the specified value (exclusive).

What is seed in random Kotlin?

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.


My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random()

TL;DR Kotlin >= 1.3, one Random for all platforms

As of 1.3, Kotlin comes with its own multi-platform Random generator. It is described in this KEEP. The extension described below is now part of the Kotlin standard library, simply use it like this:

val rnds = (0..10).random() // generated random from 0 to 10 included

Kotlin < 1.3

Before 1.3, on the JVM we use Random or even ThreadLocalRandom if we're on JDK > 1.6.

fun IntRange.random() = 
       Random().nextInt((endInclusive + 1) - start) + start

Used like this:

// will return an `Int` between 0 and 10 (incl.)
(0..10).random()

If you wanted the function only to return 1, 2, ..., 9 (10 not included), use a range constructed with until:

(0 until 10).random()

If you're working with JDK > 1.6, use ThreadLocalRandom.current() instead of Random().

KotlinJs and other variations

For kotlinjs and other use cases which don't allow the usage of java.util.Random, see this alternative.

Also, see this answer for variations of my suggestion. It also includes an extension function for random Chars.


Generate a random integer between from(inclusive) and to(exclusive)

import java.util.Random

val random = Random()

fun rand(from: Int, to: Int) : Int {
    return random.nextInt(to - from) + from
}

As of kotlin 1.2, you could write:

(1..3).shuffled().last()

Just be aware it's big O(n), but for a small list (especially of unique values) it's alright :D


Possible Variation to my other answer for random chars

In order to get random Chars, you can define an extension function like this

fun ClosedRange<Char>.random(): Char = 
       (Random().nextInt(endInclusive.toInt() + 1 - start.toInt()) + start.toInt()).toChar()

// will return a `Char` between A and Z (incl.)
('A'..'Z').random()

If you're working with JDK > 1.6, use ThreadLocalRandom.current() instead of Random().

For kotlinjs and other use cases which don't allow the usage of java.util.Random, this answer will help.

Kotlin >= 1.3 multiplatform support for Random

As of 1.3, Kotlin comes with its own multiplatform Random generator. It is described in this KEEP. You can now directly use the extension as part of the Kotlin standard library without defining it:

('a'..'b').random()

You can create an extension function similar to java.util.Random.nextInt(int) but one that takes an IntRange instead of an Int for its bound:

fun Random.nextInt(range: IntRange): Int {
    return range.start + nextInt(range.last - range.start)
}

You can now use this with any Random instance:

val random = Random()
println(random.nextInt(5..9)) // prints 5, 6, 7, 8, or 9

If you don't want to have to manage your own Random instance then you can define a convenience method using, for example, ThreadLocalRandom.current():

fun rand(range: IntRange): Int {
    return ThreadLocalRandom.current().nextInt(range)
}

Now you can get a random integer as you would in Ruby without having to first declare a Random instance yourself:

rand(5..9) // returns 5, 6, 7, 8, or 9

In Kotlin SDK >=1.3 you can do it like

import kotlin.random.Random

val number = Random.nextInt(limit)