【Java开源代码栏目提醒】:网学会员--在 Java开源代码编辑为广大网友搜集整理了:TextNotRepeatNum.java绩等信息,祝愿广大网友取得需要的信息,参考学习。
package com.zf.s8;//创建一个包
import java.util.ArrayList;//引入类
import java.util.List;
import java.util.Random;
public class TextNotRepeatNum {//操作生成不重复随机数的序列的类
private int min;//最小数
private int max;//最大数
public TextNotRepeatNum(){//构造方法初始化变量
this.min = 0;
this.max = 10;
}
public TextNotRepeatNum(int min, int max){//带参数构造方法初始化变量
this();//调用上面的构造方法
if (max >= min){
this.min = min;
this.max = max;
} else {
System.out.println("最大值小于最小值,按缺省值进行赋值!");
}
}
public Integer[] getRandomByObviate(int length) {//运用排除法生成不重复的随机数序列
if (length <= 0) {//判断传入的数值
return new Integer[0];
} else if (length > (this.max - this.min)) {
System.out.println("长度不能达到:" + length + ", 长度只能是:"
+ (this.max - this.min));
length = this.max - this.min;//重新赋值
}
Random random = new Random();//用于生成随机对象
List result = new ArrayList();//创建列表对象
while (result.size() < length) {
// 将[min, max]区间等价于min + [0, max - min + 1) 生成随机数
Integer randnum = new Integer(this.min + random.nextInt(this.max - this.min + 1));
if (!result.contains(randnum)){//判断列表中是否包含对象
result.add(randnum);//添加整型对象
}
}
return (Integer[])result.toArray(new Integer[0]);//将列表转换成整型数组返回
}
public Integer[] getRandomByFilter(int length) {//运用筛选法生成不重复的随机数序列
if (length <= 0) {
return new Integer[0];
} else if (length > (this.max - this.min)) {
System.out.println("长度不能达到:" + length + ", 长度只能是:"
+ (this.max - this.min));
length = this.max - this.min;
}
int numLength = this.max - this.min + 1;//初始化列表长度
List list = new ArrayList();
for (int i=this.min; i<= this.max; i++){//循环依次获得整数
list.add(new Integer(i));//在列表中添加整型数据
}
Random rd = new Random();// 用于生成随机下标
List result = new ArrayList();//创建列表对象
while (result.size() < length) {
int index = rd.nextInt(numLength);// 生成在[0,numLength)范围内的下标
result.add(list.get(index));//将下标为index的数字对象放入列表对象中
list.remove(index);//移除下标为index的数字对象
numLength --; // 候选队列长度减去1
}
return (Integer[])result.toArray(new Integer[0]);//将列表转换成整型数组返回
}
public static void showArray(Integer[] data){//显示数组元素
if (data != null){//判断数组是否为空
for (int i=0; i<data.length; i++){//循环显示数组数据
System.out.print(data[i] + "\t");
}
}
System.out.println();//换行
}
public static void main(String []args){//java程序主入口处
TextNotRepeatNum test = new TextNotRepeatNum(3, 12);
System.out.println("1.运用排除法生成不重复的随机数序列");
showArray(test.getRandomByObviate(6));
System.out.println("2.运用筛选法生成不重复的随机数序列");
showArray(test.getRandomByFilter(6));
}
}
上一篇:
TextMuliticastServer.java
下一篇:
数字图像的可逆数字水印研究