簡體   English   中英

Scala - 用隨機數填充 Seq,不重復且始終具有相同大小

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

我想創建一個大小始終等於 3 的Ints Seq 。如果一個數字介於 0 到 10 之間,那么我想始終返回一個由 3 個相同數字組成的Seq 如果數字來自其他范圍,那么我想返回 3 個隨機數的Seq ,但沒有重復。 我為此創建了一個代碼:

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的大小為 1 或 2(刪除重復項后)。 如何將此代碼更改為類似但始終返回長度為 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)
}

注意:如果第 1 個數字在 0 到 10 范圍之外,第 2 和/或第 3 個數字仍然僅限於 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,這可能需要很長時間,因此最好添加另一個變量來跟蹤試驗次數以獲得具有所需長度的序列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM