使用Scala生成随机数的方法示例
2019-06-16 15:13
761 查看
一.使用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 }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- 使用timer方法生成一个定时器,每隔一段时间输出一个随机数
- Linux Shell 生成随机数和随机字符串的方法示例
- java使用dom4j生成与解析xml文档的方法示例
- 使用c语言生成随机数的示例分享
- 使用PHP生成随机数方法详解
- 随机生成一个n bit位的长整数(随机函数的使用,特定区间随机数的生成方法)
- 不使用Math.random方法生成随机数(随机数生成器)
- 两种模型选择和超参数调整方法及Spark MLlib使用示例(Scala/Java/Python)
- 利用Golang生成整数随机数方法示例
- java 方法使用实例----生成随机数
- Python使用pyh生成HTML文档的方法示例
- Python简单生成随机数的方法示例
- asp.net使用ashx生成图形验证码的方法示例
- iTEXT生成PDF文件使用方法 实例 示例 Servlet输出PDF文档方法
- Java生成随机数的2种示例方法代码
- sql 生成100W条指定位数的随机数的方法(只花费了不足1分钟)(整理)
- window.scrollTo()方法使用示例
- 使用POI生成Excel文件及使用POI在EXCEL文件中插入图片的方法
- .NET生成随机数方法
- 使用ASP.NET AJAX异步调用Web Service和页面中的类方法(4):异步通讯层生成的客户端代理类、使用HTTP GET进行调用