Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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()
over 4 years ago · Santiago Trujillo Report

0

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)
    }
over 4 years ago · Santiago Trujillo Report

0

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()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!