使用Scala生成隨機(jī)數(shù)的方法示例
一.使用Scala生成隨機(jī)數(shù)
1.簡(jiǎn)單版本:
/* 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.復(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中找,如果沒有則添加
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、每次生成一個(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 }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java 關(guān)于遞歸的調(diào)用機(jī)制精細(xì)解讀
關(guān)于遞歸是什么,簡(jiǎn)單的說(shuō): 遞歸就是方法自己調(diào)用自己,每次調(diào)用時(shí) 傳入不同的變量.遞歸有助于編程者解決復(fù)雜的問(wèn)題,同時(shí)可以讓代碼變得簡(jiǎn)潔2021-10-10Java中Comparable與Comparator的區(qū)別解析
這篇文章主要介紹了Java中Comparable與Comparator的區(qū)別解析,實(shí)現(xiàn)Comparable接口,重寫compareTo方法,一般在實(shí)體類定義的時(shí)候就可以選擇實(shí)現(xiàn)該接口,提供一個(gè)默認(rèn)的排序方式,供Arrays.sort和Collections.sort使用,需要的朋友可以參考下2024-01-01使用JMX監(jiān)控Zookeeper狀態(tài)Java API
今天小編就為大家分享一篇關(guān)于使用JMX監(jiān)控Zookeeper狀態(tài)Java API,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03Java中JFinal框架動(dòng)態(tài)切換數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了Java中JFinal框架動(dòng)態(tài)切換數(shù)據(jù)庫(kù)的方法,本文通過(guò)兩種方法結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03通俗易懂學(xué)習(xí)java并發(fā)工具類-Semaphore,Exchanger
這篇文章主要介紹了java并發(fā)工具類-Semaphore,Exchanger,java并發(fā)工具類有很多,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,下面小編帶大家來(lái)一起學(xué)習(xí)一下吧2019-06-06深入dom4j使用selectSingleNode方法報(bào)錯(cuò)分析
本篇文章是對(duì)dom4j使用selectSingleNode方法報(bào)錯(cuò)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05MyBatis之自查詢使用遞歸實(shí)現(xiàn) N級(jí)聯(lián)動(dòng)效果(兩種實(shí)現(xiàn)方式)
這篇文章主要介紹了MyBatis之自查詢使用遞歸實(shí)現(xiàn) N級(jí)聯(lián)動(dòng)效果,本文給大家分享兩種實(shí)現(xiàn)方式,需要的的朋友參考下吧2017-07-07