新聞中心
今天就跟大家聊聊有關(guān)使用Scala怎么生成隨機(jī)數(shù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、微信小程序開(kāi)發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了騰沖免費(fèi)建站歡迎大家使用!
一.使用Scala生成隨機(jī)數(shù)
1.簡(jiǎn)單版本:
/*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ù)的隨機(jī)數(shù)
1、循環(huán)獲取隨機(jī)數(shù),再到 list中找,如果沒(méi)有則添加
def randomNew(n:Int)={ var resultList:List[Int]=Nil while(resultList.length
這種只適合數(shù)量比較少的情況
2、每次生成一個(gè)隨機(jī)數(shù)index,將index作為數(shù)組下標(biāo)取相應(yīng)的元素,然后去除該元素,下一次生成隨機(jī)數(shù)的范圍減1,
def randomNew2(n:Int)={ var arr= 0 to 20 toArray var outList:List[Int]=Nil var border=arr.length//隨機(jī)數(shù)范圍 for(i<-0 to n-1){//生成n個(gè)數(shù) val index=(new Random).nextInt(border) println(index) outList=outList:::List(arr(index)) arr(index)=arr.last//將最后一個(gè)元素?fù)Q到剛?cè)∽叩奈恢? arr=arr.dropRight(1)//去除最后一個(gè)元素 border-=1 } outList}
看完上述內(nèi)容,你們對(duì)使用Scala怎么生成隨機(jī)數(shù)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
文章名稱:使用Scala怎么生成隨機(jī)數(shù)
當(dāng)前地址:http://fisionsoft.com.cn/article/gsdiid.html