Jaoa
Jaoa

Reputation: 95

How to Shuffle a List in Scala

I am trying to read a text file and append its values to an array and print its elements randomly to the screen.

I am using Random from the util library but it's not outputting as expected.

Below is my code

import scala.io.Source
import scala.util.Random

object Scala  
{ 

    def main(args: Array[String])  
    { 
        val lines = Source.fromFile("text.txt").getLines.toArray
        val modified_lines = Random.shuffle(List(lines))
        for (line <- modified_lines) {
            println(line)
        }

    } 
} 

and I have a text file that contains

1. ABC
2. ABC
3. ABC
4. ABC
5. ABC
6. ABC

So in the end I'd like to print them to the screen such as

5. ABC
2. ABC
...
6. ABC

Upvotes: 0

Views: 199

Answers (1)

fenixil
fenixil

Reputation: 2124

With statement List(lines) you create list of arrays and shuffle method tries to shuffle list with 1 element:

val lines = Source.fromFile("text.txt").getLines.toArray
val list: List[Array[string]] = List(lines) <-- that's not what you need I suppose
val modified_lines = Random.shuffle(list)

Instead of creating a list with an array, just get it from getLines:

val lines = Source.fromFile("text.txt").getLines.toList
Random.shuffle(lines).foreach(println)

Upvotes: 2

Related Questions