EManual
EManual

Reputation: 341

How to shuffle elements of Mutable list in Kotlin?

I wanted to create a MutableList of alphabets and then shuffle them and store it in another MutableList.

I used shuffle() function but it resulted in the original list being shuffled as well which I didn't wanted to happen as I will be using the original list to map it with new shuffled one.

fun main(){

    val alphabets = ('A'..'Z').toMutableList()
    
    var shuffAlp = alphabets
    shuffAlp.shuffle()

    println(alphabets)
    println(shuffAlp)
}

So I had to create two mutable list and then shuffle one of them

val alphabets = ('A'..'Z').toMutableList()
var shuffAlp = ('A'..'Z').toMutableList()
shuffAlp.shuffle()

This might be a trivial question but is there any other way where I do not have to create two same list?

Upvotes: 7

Views: 9219

Answers (1)

Animesh Sahu
Animesh Sahu

Reputation: 8106

shuffle does shuffle into original list, shuffled do and return new list.

And same behavior is for sort & sorted, sortBy & sortedBy, reverse & asReversed:

fun main(){
    val alphabets = ('A'..'Z').toMutableList()
    val shuffAlp = alphabets.shuffled()

    println(alphabets)
    println(shuffAlp)
}

Result:

[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]
[U, B, A, N, H, R, O, K, X, C, W, E, Q, P, J, Z, L, Y, S, M, I, D, V, F, G, T]

Upvotes: 15

Related Questions