简体   繁体   English

Scala - 用随机数填充 Seq,不重复且始终具有相同大小

[英]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.我想创建一个大小始终等于 3 的Ints Seq 。如果一个数字介于 0 到 10 之间,那么我想始终返回一个由 3 个相同数字组成的Seq If number is from other range, then I want to return a Seq of 3 random numbers, but without duplicates.如果数字来自其他范围,那么我想返回 3 个随机数的Seq ,但没有重复。 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).但在第二种情况下,我可以随机化 1、2 或 3 个相同的数字,然后我的Seq的大小为 1 或 2(删除重复项后)。 How could I change this code to similar but always return Seq with length 3?如何将此代码更改为类似但始终返回长度为 3 的Seq

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.注意:如果第 1 个数字在 0 到 10 范围之外,第 2 和/或第 3 个数字仍然仅限于 0 到 100 范围。

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 .这可以通过提取< 11的情况或使用Set而不是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.请注意,如果序列的大小远大于 3,这可能需要很长时间,因此最好添加另一个变量来跟踪试验次数以获得具有所需长度的序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM