Reputation: 439
in Kotlin, I'm trying to, for example, get 5 numbers into an Array, List or ArrayList, the 5 numbers to come from 6 to 30. Been looking online and I ended up getting the following to work, however it isn't picking unique numbers for the list, so it could pick something like 6,6,20,24,24.
val cardNumbersCol1 = (1..5).map { (6..30).random() }
Is there a better way to do this?
I'm still learning as I go.
Thanks
Upvotes: 1
Views: 1131
Reputation: 3305
Option 1: You can create Set
because set cannot have duplicate elements by definition. Therefore, you won't need to worry about duplicate numbers:
val cardNumbersCol1 = mutableSetOf<Int>()
while (cardNumbersCol1.size != 5) {
cardNumbersCol1.add(Random.nextInt(6, 30))
}
Option 2: You can generate range from 6 to 30 use shuffled()
function to shuffle the list. Finally, you can take first 5 items from the list and they'll be unique also:
val cardNumbersCol1 = (6..30).shuffled().take(5).toSet()
Upvotes: 2
Reputation: 31710
Another approach is to use a sequence generator to produce a sequence of random Ints, and then filter by distinct and take the first few that you want:
fun randomGenerator(from: Int,
until: Int,
random: Random = Random.Default): Sequence<Int> = sequence {
while(true) {
yield(random.nextInt(from, until))
}
}
fun main() {
val someRandomInts: Set<Int> =
randomGenerator(6, 30)
.distinct()
.take(5)
.toSet()
println(someRandomInts)
}
Or, you can define an extension function on IntRange
to make this a bit prettier:
fun IntRange.randomSequence(random: Random = Random.Default): Sequence<Int> = sequence {
while(true) {
yield([email protected](random))
}
}
And to use:
val someRandomInts: Set<Int> =
(6..30).randomSequence().distinct().take(5).toSet()
Upvotes: 2
Reputation: 3893
You can populate set with manual checking items:
var cardNumbersCol1 = mutableSetOf<Int>()
while (cardNumbersCol1.size < 5) {
val item = (6..30).random()
cardNumbersCol1.add(item)
}
Upvotes: 1