簡體   English   中英

如何通過scala生成不同的隨機數? 並且數量應該盡可能短

[英]How to generate different random number by scala? and the number should be as short as possible

如何通過scala生成不同的隨機數? 我想生成唯一的ID來標記數據,同時ID應該足夠短以節省成本?

由於您的要求是

  1. 隨機數

  2. 獨特

  3. 越短越好

然后,我認為您應該考慮使用scala.util.Random.shuffle ,例如,

scala.util.Random.shuffle(1 to 30)

上面的代碼將生成一個Vector ,其中包含從1到30的唯一隨機數(就位置而言),例如Vector(26, 10, 7, 29, 11, 14, 16, 1, 12, 9, 28, 6, 19, 4, 27, 8, 13, 18, 30, 20, 23, 5, 21, 24, 17, 25, 2, 15, 22, 3)

基本上,它可以滿足您的所有需求。

如果您希望通過SetList獲得結果,只需調用toSettoList方法即可。

nextInt可以實現相同的目的,但是您可能需要很多邏輯和重試機制。

嘗試這個:

import util.Random.nextInt
Stream.continually(nextInt(100)).take(10)

或者您可以在控制台中查看生成的數字:

 import util.Random.nextInt
 val res = Stream.continually(nextInt(100)).take(10)
 res.foreach(println)

因此,基本上,您可以使用“設置”生成唯一的隨機數。

val r = scala.util.Random
var temp:Int = 0
var s:Set[Int] = Set()

var i:Int = 0
while(i<n){
    temp = r.nextInt(range)   //random number will be checked whether it is already in the set or not
    if(!s.contains(temp)){    //if the random number is not in the set
      s=s+temp;               //random number is added in the set
      i+=1
    }
  }
s.toArray                     //converts the set into array

暫無
暫無

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

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