An example of how to generate random numbers using Scala

Time:2019-10-18

Using Scala to generate random numbers

1. Simple version:


/*
1.you can use scala.util.Random.nextInt(10) to produce a number between 1 and 10
2.at the same time,you nextInt(100) to produce a number between 1 and 100
*/
object Test {
 def main(args: Array[String]) {
  var i = 0
  while(i < 10)
   var str = scala.util.Random.nextInt(100).toString
   println(str)
   i = i+1
  }
 }
}

 

 

2. Complex version:


object Test{
 def main(args: Array[String]): Unit = {
  val wordPerMessage = 4
  var i = 0
  while(i<10){
   /*
   1.the (1 to 1) is meaning that only have one circulation.
   */
   (1 to 1).foreach { messageNum => {
    //[There's only three cycle]
    val str: Seq[String] = (1 to wordPerMessage).map(x => scala.util.Random.nextInt(10).toString)
    val str1 = str.mkString(" ")//separate str1 with space
    println(str)
    }
   }
   i = i +1
  }
 }
}

PS: Scala generates a set of non repeated random numbers

1. Cycle to get random numbers and find them in the list. If not, add them.


def randomNew(n:Int)={
 var resultList:List[Int]=Nil
 while(resultList.length<n){
  val randomNum=(new Random).nextInt(20)
  if(!resultList.exists(s=>s==randomNum)){
   resultList=resultList:::List(randomNum)
  }
 }
 resultList
}

This is only suitable for a small number of cases

2. Each time a random number index is generated, the index is used as the array subscript to get the corresponding element, and then the element is removed, and the next generation range of random number is reduced by 1.

def randomNew2(n:Int)={
 var arr= 0 to 20 toArray
 var outList:List[Int]=Nil
 Var border = arr.length // random number range
 For (I < - 0 to n-1) {// N numbers generated
  val index=(new Random).nextInt(border)
  println(index)
  outList=outList:::List(arr(index))
  Arr (index) = arr.last // change the last element to the position just removed
  Arr = arr.dropright (1) // remove the last element
  border-=1
 }
 outList
}

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

How to check the package according to the command in CentOS

In our work, we often encounter that we want to use a command machine that is not installed, but we don’t know which package the command is in (source compilation is not covered in this article). Here is a rather stupid method to help us solve this problem. Explain:Blue = command name Light green = […]