lundi 4 novembre 2019

Scala - fill Seq with random numbers, without duplicates and always with same size

I would like to create a Seq of Ints with size always equal to 3. If a number is from range 0 to 10 then I want to return always a Seq of 3 same numbers. If number is from other range, then I want to return a Seq of 3 random numbers, but without duplicates. I created a code for this:

object Simulator {
  def toSeq(value: => Int): Seq[Int] = Seq.fill(3)(value).distinct

  def shuffle(): Seq[Int] = {
    val seq = 0 to 100
    val number = Random.nextInt(seq.length)
    number match {
      case _ if 0 to 10 contains number => toSeq(number)
      case _ => toSeq(Random.nextInt(seq.count(_ != number)))
    }
  }
}

But in the second case I can randomize 1, 2 or 3 same numbers and then size of my Seq is 1 or 2 (after remove duplicates). How could I change this code to similar but always return Seq with length 3?




Aucun commentaire:

Enregistrer un commentaire