Random в диапазоне kotlin

Finding out random numbers in Kotlin

We have a couple of different ways to generate random numbers in Java. Starting from Kotlin 1.3, one new package kotlin.random was introduced for a pseudo-random generation. So, if your project is using 1.3 or later Kotlin version, you can use this package.

In this post, I will mainly show you a couple of different methods to generate random numbers. If you get confused about which one to prefer, just use kotlin.random.

java.util package provides one class called Random to create random numbers. To use this class on Kotlin, import it :

Here, the parameter 20 is optional. It is called bound. This is the upper bound of random numbers. It will create one random number between 0(inclusive) and 20(exclusive). This value should always be positive.

Random class also provides other methods to generate random boolean, double, float, bytes and long.

ThreadLocalRandom can be used to generate positive or negative random numbers as double, integer or long. It is useful in the multithreaded environment because this is a thread-safe random number generator. It generates different Random number generator for each thread and thus provides more concurrency safety.

import java.util.concurrent.ThreadLocalRandom 
import java.util.concurrent.ThreadLocalRandom fun main(args: Arraystring>)  print(ThreadLocalRandom.current().nextInt(10,20)) >

nextInt takes two parameters. The first one is the lower bound(inclusive) and the second one is the upper bound(exclusive).

This is another way to generate a random number. We will shuffle one list of numbers and pick the first or the last value from the shuffled list :

fun main(args: Arraystring>)  println((0..50).shuffled().first()) println((0..50).shuffled().last()) >

It works. But an expensive operation for a large list of numbers.

Kotlin Random class provides a couple of different methods to create random integer, double, long, float, boolean and bits/bytes. To use this class, you need to import :

import kotlin.random.Random 

Use the below methods to create a random value :

import kotlin.random.Random fun main(args: Arraystring>)  println(Random.nextBoolean()) println(Random.nextInt()) println(Random.nextDouble()) println(Random.nextLong()) println(Random.nextFloat()) >

nextBoolean: Generates one random boolean value nextInt: Generates one random integer between Int.MIN_VALUE and Int.MAX_VALUE (inclusive). nextDouble: Generates one random double between 0 (inclusive) and 1 (exclusive). nextLong: Generates one random long between Long.MIN_VALUE and Long.MAX_VALUE (inclusive). nextFloat: Generates one random float between 0 (inclusive) and 1 (exclusive).

It also provides methods to create random numbers in user given range :

import kotlin.random.Random fun main(args: Arraystring>)  println(Random.nextInt(10,20)) println(Random.nextDouble(10.5,20.5)) println(Random.nextLong(10,100)) >

It generates random values in the range provided. The first argument is the inclusive lower bound and the second argument is the exclusive upper bound.

Similarly, we can also create random bits and bytes :

fun nextBits(bitCount: Int): Int fun nextBytes(array: ByteArray): ByteArray fun nextBytes(size: Int): ByteArray fun nextBytes(array: ByteArray, fromIndex: Int, toIndex: Int): ByteArray 

Kotlin random with ranges :

Kotlin Ranges comes with a method called random() to get one random value :

fun main(args: Arraystring>)  println((1..100).random()) println(('a'..'z').random()) >

This is more preferred than the shuffled method we have seen above.

We can create one instance of a random number generator with an integer or long value as its seed. The generator object depends on the seed we provide. If we use the same seed for two instances, both instances will generate the same sequence of random values in the same version of Kotlin runtime.

import kotlin.random.Random fun main(args: Arraystring>)  println(Random(20).nextInt()) println(Random(20).nextInt()) >

Here, both will print the same result as the seed is the same for both instances.

Источник

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.

Note: Future versions of Kotlin may change the algorithm of this seeded number generator so that it will return a sequence of values different from the current one for a given seed.

On JVM the returned generator is NOT thread-safe. Do not invoke it from multiple threads without proper synchronization.

import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array) < //sampleStart fun getRandomList(random: Random): List= List(10) < random.nextInt(0, 100) >val randomValues1 = getRandomList(Random(42)) // prints the same sequence every time println(randomValues1) // [33, 40, 41, 2, 41, 32, 21, 40, 69, 87] val randomValues2 = getRandomList(Random(42)) // random with the same seed produce the same sequence println("randomValues1 == randomValues2 is $") // true val randomValues3 = getRandomList(Random(0)) // random with another seed produce another sequence println(randomValues3) // [14, 48, 57, 67, 82, 7, 61, 27, 14, 59] //sampleEnd >

Returns a repeatable random number generator seeded with the given seed Long value.

Two generators with the same seed produce the same sequence of values within the same version of Kotlin runtime.

Note: Future versions of Kotlin may change the algorithm of this seeded number generator so that it will return a sequence of values different from the current one for a given seed.

On JVM the returned generator is NOT thread-safe. Do not invoke it from multiple threads without proper synchronization.

import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array) < //sampleStart fun getRandomList(random: Random): List= List(10) < random.nextInt(0, 100) >val randomValues1 = getRandomList(Random(42)) // prints the same sequence every time println(randomValues1) // [33, 40, 41, 2, 41, 32, 21, 40, 69, 87] val randomValues2 = getRandomList(Random(42)) // random with the same seed produce the same sequence println("randomValues1 == randomValues2 is $") // true val randomValues3 = getRandomList(Random(0)) // random with another seed produce another sequence println(randomValues3) // [14, 48, 57, 67, 82, 7, 61, 27, 14, 59] //sampleEnd >

Источник

Генерация случайных чисел в Kotlin

В этой статье рассматриваются различные способы генерации случайных чисел в указанном диапазоне в Kotlin.

1. Использование random() функция

Простой подход для извлечения произвольного элемента из указанного диапазона заключается в использовании random() функция.

Выход (будет варьироваться):

7
5
9
8
8

Вы можете вызвать его без аргументов или с Random объект как источник случайности.

Выход (будет варьироваться):

7
7
9
5
6

2. Использование Random class

Kotlin предлагает Random класс в kotlin.random пакет, который может генерировать случайные числа. Вы можете использовать его nextInt() функция для получения псевдослучайного целочисленного значения от 0 (включительно) до заданного значения (исключительно).

Ниже приведен простой пример, демонстрирующий использование этой функции, которая генерирует псевдослучайное число между start а также end :

Выход (будет варьироваться):

9
6
5
9
5

Это работает как nextInt(end — start + 1) будет генерировать случайное число от 0 до (end — start) и добавление start ему даст случайное число между start а также end .

The nextInt() функция перегружена для генерации целочисленного случайного значения, равномерно распределенного между указанным диапазоном.

Выход (будет варьироваться):

8
5
6
8
6

3. Использование Math.random() функция

Другим приемлемым способом является использование Math.random() функция, которая возвращает псевдослучайное двойное значение в диапазоне [0.0, 1.0) .

Выход (будет варьироваться):

7
7
8
8
5

Он работает как Math.random() генерирует случайный двойник в диапазоне [0.0, 1.0) . При умножении на ((end — start) + 1) , нижний предел остается равным 0, а верхний предел становится (end — start, end — start + 1) . При приведении к Int и добавлении start , диапазон становится [start, end] .

4. Использование SecureRandom class

Чтобы получить криптографически стойкий генератор случайных чисел, рассмотрите возможность использования SecureRandom класс из java.security упаковка. Вот рабочий пример:

Источник

Генерировать случайные целые числа между указанными диапазонами в Kotlin

В этом посте будет обсуждаться, как генерировать случайные целые числа между указанным диапазоном в Kotlin.

1. Использование Random class

The Random.nextInt() функция генерирует Int случайное значение, равномерно распределенное между 0 (включительно) и указанной границей (исключительно). Чтобы сгенерировать случайное целое число между low а также high , можно использовать выражение Random.nextInt(high — low + 1) + low , как показано ниже.

Это работает как Random.nextInt(high — low + 1) генерирует случайное целое число от 0 до (high — low) , и добавление low к этому приведет к случайному целому числу между low к high . Чтобы получить криптографически стойкий генератор случайных целых чисел, рассмотрите возможность использования java.security.SecureRandom учебный класс.

2. Использование диапазона Kotlin

Кроме того, вы можете создать диапазон между low а также high , и вернуть из него случайный элемент с помощью random() функция.

3. Использование Math class

Вы также можете использовать Math.random() функция для возврата псевдослучайного двойного числа в пределах диапазона [0.0, 1.0) . Идея состоит в том, чтобы использовать выражение (Math.random() * (high — low + 1)).toInt() + low генерировать случайное число между low а также high .

Это работает с тех пор Math.random() функция генерирует случайный двойник в диапазоне [0.0, 1.0) . Когда вы умножаете его на (high — low) + 1 , верхний предел становится (high — low, high — low + 1) . После приведения его к int диапазон становится [0, high — low] . Добавление low к нему диапазон становится [low, high] .

Это все о генерации случайных целых чисел между указанными диапазонами в Kotlin.

Средний рейтинг 5 /5. Подсчет голосов: 12

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Источник

How can I get a random number in Kotlin?

Kotlin provides multiple ways to generate a random number. In this article, we will see different ways to generate a random number and access it throughout the program.

Example – Using Random class

Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.

As per the Kotlin documentation, the companion object Random.Default is the default instance of Random class. In the following example, we will generate a list of random values with int (1-30) .

Example

import kotlin.random.Random fun main() < val myRandomValues = List(5) < Random.nextInt(0, 30) >// Prints a new sequence every time println(myRandomValues) >

Output

It generated the following random numbers. You may get a different set of numbers, as the output is random in nature.

Example – Using random()

Kotlin does provide a random() function to generate random numbers. It takes a series of numbers as an input and it returns a random Int as an output.

Example

Output

On execution, it produced the following output −

Example – Using shuffled()

Kotlin does provide another method to generate random numbers between a sequence. We can use shuffled() to generate a random number in between 1 to 100.

Example

Output

On execution, it produced the following output. It could be different in your case, as the output is random in nature.

Источник

Читайте также:  Парсер xml для php
Оцените статью