繁体   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