Obtenir un nombre aléatoire en Kotlin

Obtenir un nombre aléatoire en Kotlin

1. introduction

Ce court tutoriel montrera comment générer un nombre aléatoire à l’aide de Kotlin.

2. Nombre aléatoire utilisantjava.lang.Math

Le moyen le plus simple de générer un nombre aléatoire dans Kotlin est d'utiliserjava.lang.Math. L'exemple ci-dessous générera un nombre double aléatoire compris entre 0 et 1.

@Test
fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() {
    val randomNumber = Math.random()
    assertTrue { randomNumber >= 0 }
    assertTrue { randomNumber < 1 }
}

3. Nombre aléatoire utilisantThreadLocalRandom

Nous pouvons également utiliserjava.util.concurrent.ThreadLocalRandom pour générer une valeur double, entière ou longue aléatoire. Integer and long values generated this way can be both positive or negative.

ThreadLocalRandom is thread-safe and provides better performance in a multithreaded environment car il fournit un objetRandom séparé pour chaque thread et réduit ainsi les conflits entre les threads:

@Test
fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() {
    val randomDouble = ThreadLocalRandom.current().nextDouble()
    val randomInteger = ThreadLocalRandom.current().nextInt()
    val randomLong = ThreadLocalRandom.current().nextLong()
    assertTrue { randomDouble >= 0 }
    assertTrue { randomDouble < 1 }
    assertTrue { randomInteger >= Integer.MIN_VALUE }
    assertTrue { randomInteger < Integer.MAX_VALUE }
    assertTrue { randomLong >= Long.MIN_VALUE }
    assertTrue { randomLong < Long.MAX_VALUE }
}

4. Nombre aléatoire utilisant Kotlin.js

Nous pouvons également générer un double aléatoireusing the Math class from the kotlin.js library.

@Test
fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() {
    val randomDouble = Math.random()
    assertTrue { randomDouble >=0 }
    assertTrue { randomDouble < 1 }
}

5. Nombre aléatoire dans une plage donnée en Kotlin pur

En utilisant pur Kotlin, nous pouvonscreate a list of numbers, shuffle it and then take the first element à partir de cette liste:

@Test
fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() {
    val randomInteger = (1..12).shuffled().first()
    assertTrue { randomInteger >= 1 }
    assertTrue { randomInteger <= 12 }
}

6. Nombre aléatoire dans une plage donnée en utilisantThreadLocalRandom

ThreadLocalRandom présenté dans la section 3 peut également être utilisé pour générer un nombre aléatoire dans une plage donnée:

@Test
fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() {
    val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0)
    val randomInteger = ThreadLocalRandom.current().nextInt(1, 10)
    val randomLong = ThreadLocalRandom.current().nextLong(1, 10)
    assertTrue { randomDouble >= 1 }
    assertTrue { randomDouble < 10 }
    assertTrue { randomInteger >= 1 }
    assertTrue { randomInteger < 10 }
    assertTrue { randomLong >= 1 }
    assertTrue { randomLong < 10 }
}

7. Pseudo vs générateurs de nombres aléatoires sécurisés

Les implémentations JDK standard dejava.util.Random utilisent unLinear Congruential Generator pour fournir des nombres aléatoires. Le problème avec cet algorithme est qu’il n’est pas puissant sur le plan cryptographique et que ses résultats pourraient être prédits par des attaquants.

Pour résoudre ce problème,we should use java.security.SecureRandom dans les endroits où nous avons besoin d'une bonne sécurité:

fun whenRandomNumberWithJavaSecureRandom_thenResultsInGivenRanges() {
    val secureRandom = SecureRandom()
    secureRandom.nextInt(100)
    assertTrue { randomLong >= 0 }
    assertTrue { randomLong < 100 }
}

SecureRandom produit des valeurs aléatoires cryptographiquement fortes en utilisant un générateur de nombres pseudo-aléatoires cryptographiquement fort (CSPRNG).

Les applications ne doivent pas utiliser d’autres méthodes pour générer un nombre aléatoire sécurisé dans des lieux liés à la sécurité.

8. Conclusion

Dans cet article, nous avons appris quelques façons de générer un nombre aléatoire dans Kotlin.

Comme toujours, tout le code présenté dans ce tutoriel peut être trouvéover on GitHub.