Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin a list of random distinct numbers

Tags:

list

kotlin

I am creating a list of random numbers using the following approach

val randomList = List(4) { Random.nextInt(0, 100) }

However, this approach doesn't work as I want to avoid repetitions

like image 764
dddddrrrrrr Avatar asked Mar 17 '19 21:03

dddddrrrrrr


People also ask

How do I generate a random 4 digit number on Android?

Random rand = new Random(); System. out. printf("%04d%n", rand. nextInt(10000));


Video Answer


1 Answers

One way is to shuffle a Range and take as many items as you want:

val randomList = (0..99).shuffled().take(4)

This is not so efficient if the range is big and you only need just a few numbers.
In this case it's better to use a Set like this:

val s: MutableSet<Int> = mutableSetOf()
while (s.size < 4) { s.add((0..99).random()) }
val randomList = s.toList()
like image 128
forpas Avatar answered Nov 02 '22 08:11

forpas