Server Side Kotlin-14

Server Side Kotlin-14

·

2 min read

In Kotlin, the shuffle function is used to randomly rearrange the elements within a collection. : Shuffling Elements: The shuffle function is part of the Kotlin Collections API. It randomly shuffles the elements in-place within the collection.

In-Place Operation: Unlike some other functions that create new collections, shuffle modifies the original collection. It doesn't return a new collection but instead rearranges the elements within the existing one.

Usage of Random Instance: The shuffling process involves using a specified Random instance as the source of randomness. This allows for control over the randomness used in the shuffling. The shuffle function is a handy tool when you need to randomize the order of elements in a collection for various scenarios such as games, surveys, or any situation where a random sequence is desired.

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supe rgame" )  
println(games.shuffled())
val myList = mutableListOf(11, 22, 33, 44, 55)
println(myList.shuffled())

output

godot, supe rgame, unreal, monogame, bevy, unity]

[44, 33, 11, 55, 22]

(different output may generate at your computer)

collection can be retrieved in the reversed order using the reversed() function.

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supe rgame" )  
println(games.reversed())

output

[supe rgame, monogame, bevy, godot, unreal, unity]

reversed() returns a new collection with the copies of the elements. So, if you change the original collection later, this won't affect the previously obtained results of reversed().

Another reversing function - asReversed()

returns a reversed view of the same collection instance, so it may be more lightweight and preferable than reversed() if the original list is not going to change.

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supe rgame" )  
val reversedNumbers = games.asReversed()
println(reversedNumbers)

output:-

[supe rgame, monogame, bevy, godot, unreal, unity]