溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Scala怎么生成隨機數(shù)

發(fā)布時間:2021-06-25 16:44:09 來源:億速云 閱讀:375 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)使用Scala怎么生成隨機數(shù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

一.使用Scala生成隨機數(shù)

1.簡單版本:

/*1.you can use scala.util.Random.nextInt(10) to produce a number between 1 and 102.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.復(fù)雜版本:

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生成一組不重復(fù)的隨機數(shù)

1、循環(huán)獲取隨機數(shù),再到 list中找,如果沒有則添加

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}

這種只適合數(shù)量比較少的情況

2、每次生成一個隨機數(shù)index,將index作為數(shù)組下標(biāo)取相應(yīng)的元素,然后去除該元素,下一次生成隨機數(shù)的范圍減1,

def randomNew2(n:Int)={ var arr= 0 to 20 toArray var outList:List[Int]=Nil var border=arr.length//隨機數(shù)范圍 for(i<-0 to n-1){//生成n個數(shù)  val index=(new Random).nextInt(border)  println(index)  outList=outList:::List(arr(index))  arr(index)=arr.last//將最后一個元素?fù)Q到剛?cè)∽叩奈恢? arr=arr.dropRight(1)//去除最后一個元素  border-=1 } outList}

看完上述內(nèi)容,你們對使用Scala怎么生成隨機數(shù)有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI