How to shuffle (randomize) a list in Scala?

Scala | Shuffle (randomize) a list: Here, we are going to learn how to shuffle (randomize) a list in Scala?
Submitted by Shivang Yadav, on May 11, 2020

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.

Example2: 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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.