0

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.

4

3 回答 3

3
List.iterate(0,7)(_ => util.Random.nextInt(90) + 1)
  .tail
  .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.

Sort the result, and turn the List into a String with the elements separated by the string " - ".

于 2016-11-24T19:18:30.963 回答
2

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)
于 2016-11-25T04:16:57.317 回答
0
  1. Replace mutable collection with immutable
  2. Add function to add random number like:

Option 1.

def addNumber(l: List[Int], n : Int) : List[Int] = n::l 

Option 2. use generators:

for{
  i <- 0 to 6
  r = scala.util.Random
} yield  r;

Generally speaking there are number of way you can code in FP way. Rest of the code looks ok.

于 2016-11-24T19:10:34.157 回答