Kotlin shuffle arrays and lists

Update: As of 1.2 Kotlin has built in shuffle methods.

I’ve been doing some more Android development and needed a way to shuffle an array using Kotlin. It’s one of the few re-usable functions I’ve needed that isn’t already built into the standard library.

I’ve come up with a couple of extension methods to do it:

fun <T> Array<T>.shuffle(): Array<T> {
    val rng = Random()

    for (index in 0..this.size - 1) {
        val randomIndex = rng.nextInt(index)

        // Swap with the random position
        val temp = this[index]
        this[index] = this[randomIndex]
        this[randomIndex] = temp
    }

    return this
}

And the equivalent for lists, iterables, etc.:

fun <T, L : MutableList<T>> L.shuffle(): L {
    val rng = Random()

    for (index in 0..this.size - 1) {
        val randomIndex = rng.nextInt(index)

        // Swap with the random position
        val temp = this[index]
        this[index] = this[randomIndex]
        this[randomIndex] = temp
    }

    return this
}

fun <T> Iterable<T>.shuffle(): List<T> = this.toList().shuffle()

Comments