Obter um número aleatório no Kotlin

Obter um número aleatório no Kotlin

1. Introdução

Este breve tutorial demonstrará como gerar um número aleatório usando o Kotlin.

2. Número aleatório usandojava.lang.Math

A maneira mais fácil de gerar um número aleatório em Kotlin é usarjava.lang.Math. O exemplo abaixo irá gerar um número duplo aleatório entre 0 e 1.

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

3. Número aleatório usandoThreadLocalRandom

Também podemos usarjava.util.concurrent.ThreadLocalRandom para gerar um duplo aleatório, inteiro ou valor longo. 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 porque fornece um objetoRandom separado para cada thread e, portanto, reduz a contenção entre os 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. Número aleatório usando Kotlin.js

Também podemos gerar um doubleusing the Math class from the kotlin.js library aleatório.

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

5. Número aleatório em um determinado intervalo usando Kotlin puro

Usando Kotlin puro, podemoscreate a list of numbers, shuffle it and then take the first element dessa lista:

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

6. Número aleatório em um determinado intervalo usandoThreadLocalRandom

ThreadLocalRandom apresentado na seção 3 também pode ser usado para gerar um número aleatório em um determinado intervalo:

@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 Geradores de números aleatórios seguros

Implementações JDK padrão dejava.util.Random usamLinear Congruential Generator para fornecer números aleatórios. O problema com esse algoritmo é que ele não é criptograficamente forte e suas saídas podem ser previstas por invasores.

Para superar esse problema,we should use java.security.SecureRandom em lugares onde precisamos de boa segurança:

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

SecureRandom produz valores aleatórios criptograficamente fortes usando um gerador de números pseudo-aleatórios criptograficamente forte (CSPRNG).

Os aplicativos não devem usar outras maneiras de gerar um número aleatório seguro em locais relacionados à segurança.

8. Conclusão

Neste artigo, aprendemos algumas maneiras de gerar um número aleatório em Kotlin.

Como sempre, todo o código apresentado neste tutorial pode ser encontradoover on GitHub.