温馨提示×

温馨提示×

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

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

利用Scala怎么生成一个随机数

发布时间:2021-03-24 17:21:55 来源:亿速云 阅读:1036 作者:Leah 栏目:编程语言

利用Scala怎么生成一个随机数?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

一.使用Scala生成随机数

1.简单版本:

/*
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
  }
 }
}

利用Scala怎么生成一个随机数 

利用Scala怎么生成一个随机数 

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
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

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

AI