Home »
Scala
How to shuffle (randomize) a list in Scala?
By IncludeHelp Last updated : October 20, 2024
Shuffling list elements
Shuffling list elements is randomizing the index of elements of the list. So, list('A', 'B', 'C', 'D') will be shuffled as list('C', 'A', 'D', 'B').
To shuffle elements of a list we will be using the shuffle method of the Random class.
Syntax
Random.shuffle(list)
The method takes a list and returns a list that has shuffled elements in the list.
Let's take a few examples to randomize lists in Scala,
Example 1
import scala.util.Random
object MyClass {
def main(args: Array[String]) {
val list = List('A', 'B', 'C', 'D', 'E')
println("The list: " + list)
println("Shuffling list elements...")
println("Shuffled list: " + Random.shuffle(list))
}
}
Output
RUN 1:
The list: List(A, B, C, D, E)
Shuffling list elements...
Shuffled list: List(A, B, E, C, D)
RUN 2:
The list: List(A, B, C, D, E)
Shuffling list elements...
Shuffled list: List(E, D, A, B, C)
Explanation
Here, we have created a list of characters and then used the shuffle method to randomize the elements of the list.
Example 2: Creating a list using range and shuffling it
import scala.util.Random
object MyClass {
def main(args: Array[String]) {
val list = List.range(5, 10)
println("Shuffling list elements within range 5 to 10...")
println("Shuffled list : " + Random.shuffle(list))
}
}
Output
RUN 1:
Shuffling list elements within range 5 to 10...
Shuffled list : List(6, 9, 8, 7, 5)
RUN 2:
Shuffling list elements within range 5 to 10...
Shuffled list : List(5, 8, 9, 6, 7)
Explanation
Here, we have used the range method of the list to create a list within values given in the range and then used the shuffle method of Random class to shuffle list elements.