欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

使用Scala生成随机数的方法示例

时间:2021-03-20 10:02:30|栏目:JAVA代码|点击:

一.使用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
  }
 }
}

 

 

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
}

上一篇:JavaFX Metro UI 和 开发库使用简介

栏    目:JAVA代码

下一篇:Hadoop 中 HBase Shell命令的详解

本文标题:使用Scala生成随机数的方法示例

本文地址:http://www.codeinn.net/misctech/84551.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有