dddddrrrrrr
dddddrrrrrr

Reputation: 317

Kotlin a list of random distinct numbers

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

Upvotes: 11

Views: 4676

Answers (3)

Seyoum Hagos
Seyoum Hagos

Reputation: 1

Create:

 val list = (0 until 100).toMutableList()  
    val randList = mutableListOf<Int>()
    
    for (i in 0 until 4) {
        val uniqueRand = list.random()
        randList.add(uniqueRand)
        list.remove(uniqueRand)
    }

Upvotes: 0

forpas
forpas

Reputation: 164164

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()

Upvotes: 18

Sergei Voitovich
Sergei Voitovich

Reputation: 2962

One line approach to get a list of n distinct random elements. Random is not limited in any way.

val list = mutableSetOf<Int>().let { while (it.size() < n) it += Random.nextInt(0, 100) }.toList()

Upvotes: -1

Related Questions