算法题:生成不重复的随机数]生成6个1-8的随机数,要求无重复。先用数组保存随机数,然后判断是否重复,如果重复重新生成
方案一:
import java.util.Random;
public class Cai {
public static void main(String[] args) {
Random ran = new Random();
int[] arr = new int[6];
for(int i=0;i<arr.length;i++){ //生成6个无重复的随机数
arr[i] = ran.nextInt(33)+1;
for(int j=0;j<i;j++){
if(arr[i] == arr[j]){ //和前面的重复了
i--; // 如果重复了,先 -- 后 ++ 相当于下标不向前移动
break;
}
}
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
方案二
import java.util.Random;
public class differenceOfRandom2 {
public static void main(String[] args) {
Random ran = new Random();
int[] tmp = new int[8];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = i + 1;
} // tmp里面放了1 - 8
int[] arr = new int[6];
for (int i = 0; i < arr.length; i++) {
int index = ran.nextInt(tmp.length - i); //
System.out.println("index:" + index);
arr[i] = tmp[index]; //随机下标
System.out.println("arr[i]:" + arr[i]);
tmp[index] = tmp[tmp.length - 1 - i]; //
System.out.println("tmp[index]:" + tmp[index]);
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
方案三:推荐使用
import java.util.Random;
import java.util.HashSet; //集合,自动过滤重复元素
public class Cai {
public static void main(String[] args) {
Random ran = new Random();
HashSet hs = new HashSet();
for(;;){
int tmp = ran.nextInt(8)+1;
hs.add(tmp);
if(hs.size() == 6) break;
}
System.out.println(hs);
}
}