温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Scala怎么生成随机数

发布时间:2021-06-25 16:44:09 来源:亿速云 阅读:365 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关使用Scala怎么生成随机数,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一.使用Scala生成随机数

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.复杂版本:

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生成一组不重复的随机数

1、循环获取随机数,再到 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}

这种只适合数量比较少的情况

2、每次生成一个随机数index,将index作为数组下标取相应的元素,然后去除该元素,下一次生成随机数的范围减1,

def randomNew2(n:Int)={ var arr= 0 to 20 toArray var outList:List[Int]=Nil var border=arr.length//随机数范围 for(i<-0 to n-1){//生成n个数  val index=(new Random).nextInt(border)  println(index)  outList=outList:::List(arr(index))  arr(index)=arr.last//将最后一个元素换到刚取走的位置  arr=arr.dropRight(1)//去除最后一个元素  border-=1 } outList}

看完上述内容,你们对使用Scala怎么生成随机数有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI