简体   繁体   中英

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? 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?

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(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) .

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.

nextInt can achieve the same thing but you might need a lot of logic and retry mechanism for it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM