Adding shuffle() to Array<T> and ByteArray, IntArray et al


#1

Element shuffling is currently implemented for MutableList:

`public actual inline fun MutableList.shuffle() {
java.util.Collections.shuffle(this)
}

public inline fun MutableList.shuffle(random: java.util.Random) {
java.util.Collections.shuffle(this, random)
}`

Could the two variants of this method please also be added to Array<T> and the primitive type specialisations (ByteArray, IntArray, etc)? They can be useful for arrays and have efficient implementations. It would bring arrays into line with MutableList, which which Array<T> already shares many functions.

I’m currently defining my own:

`fun Array.shuffle(rnd: java.util.Random) {
// Fisher-Yates shuffle algorithm
for (i in this.size - 1 downTo 1) {
val j = rnd.nextInt(i + 1)
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
}

fun IntArray.shuffle(rnd: java.util.Random) {
val random = Util.getRandom()

// Fisher-Yates shuffle algorithm
for (i in this.size - 1 downTo 1) {
    val j = random.nextInt(i + 1)
    val temp = this[i]
    this[i] = this[j]
    this[j] = temp
}

}`


#2

PS. Does anyone know what I’m doing wrong with my code snippets that only parts of them are being rendered as preformatted text?


#3

Yes. The singel ` is used for in line code and does not work over multiple lines. Use 3 of “```kotlin” insetead and start the code on a new line.


There is currently a KEEP about a random API for Kotlin. It does not contain the addition of shuffle for arrays, but I think adding asking about adding it there might be the fastest way to get this in the language.


#4

See https://youtrack.jetbrains.com/issue/KT-25651


#5

Woops, I did not think to check issues :blush:. I still think it might be worth to consider adding this to the KEEP though. I think I’ll just mention it over there as well.


#6

@Wasabi375, thanks for your formatting help and also the pointer towards the KEEP. I wasn’t sure on the etiquette of whether to raises issues there or here. I’m assuming more serious issues as KEEPs; and wish-listy items to this discussions board?


#7

That’s the way I see it as well. But because this KEEP is already dealing with Kotlins random API (or adding one to Kotlin) I thought mentioning this feature request there would be a good idea as this is IMO part of the scope of the KEEP and maybe it’s just missing because they did not think about it. In the end the KEEP is there for community input.