Home > Software design >  Kotlin - getting random Int between 1 and 2 doesn't work with Android
Kotlin - getting random Int between 1 and 2 doesn't work with Android

Time:01-17

listOf(1, 2).random()

In IntelliJ IDE, this gives me sometimes 1 and sometimes 2

But when I run it in Android App, this gives ALWAYS 1! I tried it at least 10 times!

Next one:

(1 until 3).random()

In IntelliJ IDE, this gives me sometimes 1 and sometimes 2

But when I run it in Android App, this gives ALWAYS 1!

CodePudding user response:

What version of Kotlin are you using? There was a bug in 1.6.21 on Android (https://youtrack.jetbrains.com/issue/KT-52618/) where Kotlin's default Random would produce the same sequence of values every time you ran the app. It's fixed in 1.7.20, or you could use the Java implementation (java.util.Random). Maybe something like this:

import kotlin.random.asKotlinRandom

fun main() {
    val rnd = java.util.Random().asKotlinRandom()
    // using the Java Random as the source of randomness
    listOf(1, 2).random(rnd)
}

If you're on the newer version where it should be fixed, make sure you definitely are only getting 1s - it's unlikely you'd randomly get 1 every time, but it's not impossible, especially with only two possible outcomes. So test it with lots of attempts, ideally with a bigger pool of possible results so you can be more confident you're not just getting unlucky with a coin flip here

  • Related