简体   繁体   English

如何通过scala生成不同的随机数? 并且数量应该尽可能短

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

How to generate different random number by scala? 如何通过scala生成不同的随机数? and the number should be as short as possible.I want to generate unique id to label data, in the same time the id should be short enough to save the cost? 我想生成唯一的ID来标记数据,同时ID应该足够短以节省成本?

Since your requirement is 由于您的要求是

  1. random number 随机数

  2. unique 独特

  3. as short as possible 越短越好

Then I think you should consider to use scala.util.Random.shuffle , eg, 然后,我认为您应该考虑使用scala.util.Random.shuffle ,例如,

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

Above code will generate a Vector that contains unique random number (in terms of position) from 1 to 30, eg, 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) . 上面的代码将生成一个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)

Basically it just fulfill everything you need. 基本上,它可以满足您的所有需求。

If you prefer to get the result in Set or List , simply call toSet or toList method will do. 如果您希望通过SetList获得结果,只需调用toSettoList方法即可。

nextInt can achieve the same thing but you might need a lot of logic and retry mechanism for it. nextInt可以实现相同的目的,但是您可能需要很多逻辑和重试机制。

Try this: 尝试这个:

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

or you can check in console the numbers generated: 或者您可以在控制台中查看生成的数字:

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

So basically you can use "Set" to generate unique random numbers. 因此,基本上,您可以使用“设置”生成唯一的随机数。

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