Search code examples
scalacollectionsfunctional-programmingimmutabilityimmutable-collections

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.


Solution

  • If you need 6 unique numbers, it's easiest to randomly shuffle the entire range and just take the first six from the result:

    val numbers = util.Random.shuffle(1 to 90).take(6).sorted
    val formatted = numbers map {"%02d".format(_)} mkString " - "
    println(formatted)