Scala-用随机数填充Seq,没有重复且总是相同大小

我想创建一个Seq的{​​{1}},其大小始终等于3。如果一个数字在0到10的范围内,那么我想始终返回一个Ints的3相同的数字。如果数字来自其他范围,那么我想返回一个Seq的3个随机数,但不能重复。我为此创建了一个代码:

Seq

但是在第二种情况下,我可以将1、2或3个相同的数字随机化,然后我的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))) } } } 的大小为1或2(在删除重复项之后)。我如何才能将此代码更改为相似但总是返回长度为3的Seq

AAAGIS 回答:Scala-用随机数填充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)
}

注意:如果第一个数字在0到10范围之外,则第二个和/或第三个数字仍仅限于0到100范围。

,

这是一种递归方法:

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)

可以通过提取< 11大小写或使用Set代替Seq来进一步优化。请注意,如果序列的大小远大于3,则可能要花很长时间,因此最好添加另一个变量来跟踪试验次数,以获得具有所需长度的序列。

本文链接:https://www.f2er.com/3164240.html

大家都在问