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)
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?
def shuffle(): Seq[Int] = {
val nums = util.Random.shuffle(Seq.tabulate(101)(identity))
if (nums.head < 11) Seq.fill(3)(nums.head)
else nums.take(3)
}
Notice: if the 1st number is outside the 0-to-10 range, the 2nd and/or 3rd numbers are still only restricted to the 0-to-100 range.
Here is a recursive approach:
def threeRands(n : Int, acc : Seq[Int] = Seq()) : Seq[Int] = {
val num = Random.nextInt(n)
if(n <= 0) Seq.fill(3)(-1)
else if(n > 0 && n < 11) {
Seq.fill(3)(num)
} else {
if(acc.size==3) acc
else if(acc.contains(num)) threeRands(n, acc)
else threeRands(n, acc :+ num)
}
}
threeRands(4) //res0: Seq[Int] = List(1, 1, 1)
threeRands(13) //res1: Seq[Int] = List(9, 3, 4)
threeRands(1000) //res2: res2: Seq[Int] = List(799, 227, 668)
This can be optimized more by extracting the < 11
case or using Set
instead of Seq
. Note that if the size of sequence was much larger than 3, this could take a long time so it might be better to add another variable to keep track of number of trials to get the sequence with the required length.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.