java 使用数组生成不重复的随机数
public class TestRandom {
public static void main(String[] args) {
//定义一个数组存放需要随机的数
int[] ints = new int[33];
for (int i = 0; i < ints.length; i++) {
ints[i] = i;
}
//定义一个存放随机到的数的数组
int[] newints = new int[6];
//同时定义一个数组用来监控数据是否已经被随机到,达到去重的效果
boolean[] bs = new boolean[ints.length];
Random random=new Random();
int j;
for (int i = 0; i < newints.length; i++) {
do {
j = random.nextInt(ints.length);
} while (bs[j]);
bs[j] = true; //用来标识随机到的数据是否已经存在
newints[i]=ints[j];
}
System.out.println(Arrays.toString(newints));
}
}
//随机生成n位不重复的随机数
int n =12;
Set set = new HashSet();
Random random=new Random();
do {
set.add(random.nextInt(33));
} while (set.size()<n);
System.out.println(set.size());
System.out.println(set);