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
Random rand = new Random(); System. out. printf("%04d%n", rand. nextInt(10000));
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With