Mirko Benedetti Mirko Benedetti - 12 days ago 5
Scala Question

Immutable Scala Collection

I have this Scala code that spits out unique random numbers for the Italian lottery:

object Enalotto {
def main(args: Array[String]): Unit = {
val numbers = scala.collection.mutable.SortedSet[Int]()
val r = scala.util.Random

while(numbers.size < 6) {
numbers += r.nextInt(90) + 1
}

for ((number, index) <- numbers.view.zipWithIndex) {
if(number < 10) print("0")
print(number)
if(index < 5) print(" - ")
}

println("")
}
}


I would like to ask, how would you write the same program with an immutable collection, in a more appropriate functional-style programming?

Thanks in advance.

Answer
List.iterate(0,7)(_ => util.Random.nextInt(90) + 1)
  .tail
  .map(n => if (n<10) 0 else n)
  .sorted
  .mkString(" - ")

This is your generator and your formatter.


Explanation: I'm calling the iterate() method of the List companion object. It creates a new List of 7 elements, starting with the value 0. For every value after that it invokes the anonymous function that generates a random value.

Now we have our list. Take the tail because we're actually not interested in the starting 0 value.

Use map to zero numbers less than 10, sort the result, and turn the List into a String with the elements separated by the string " - ".