定义一个没有相同的值的数组,如 int[] a = { 4, 5, 6, 7, 8, 9, 10, 15 };
从中随机抽出指定个值,要求这些值中不能有重复的。
同类型问题的简单做法:运用ArrayList集合来实现:链接在此
同类型问题的简单做法:运用HashSet集合来实现:链接在此
运用数组,在此展示两种方法,内含详细解析
方法一:
int[] a = { 4, 5, 6, 7, 8, 9, 10, 15 }; //定义数组a为要随机抽值的数组
int n = 6;
int[] b = new int[n]; // 新建数组b,大小为指定个数n=6
int[] c = new int[a.length]; // 新建数组c,用来给数组a中各值进行标记
for (int j = 0; j < n; j++) {
b[j] = 100; //将数组b中各值全部标记为一个在数组a中不存在的数,本次设为100
}
Random random = new Random();
a: while (true) {
int r = random.nextInt(a.length); //生成随机数,值为数组a的索引值
if (c[r] == 11) {
continue; //当随机索引对应的数组c中的值为11时(说明被标记),跳出此循环,重新生成随机索引
} else {
for (int k = 0; k < n; k++) { //若对应值没被标记,就遍历数组b
if (b[k] == 100) {
b[k] = a[r]; //若数组b中的值为100(说明被标记)就将随机索引对应的数组a的值赋给数组b
c[r] = 11; //并把该随机索引对应的数组c的值标记为11
break;
} else if (k == n - 1 && b[k] != 100) {
break a; //当数组b中的值被全部遍历并赋值时,跳出总循环
}
}
}
}
for (int i = 0; i < n; i++) { //遍历打印数组b
System.out.println(b[i]);
}
方法二:
int[] a = { 4, 5, 6, 7, 8, 9, 10, 15 };
int[] b = new int[6]; // 新建数组b,大小为指定个数n=6
Random random = new Random();
b: while (true) {
for (int i = 0; i < b.length; i++) {
int t = random.nextInt(a.length); //生成随机数,值为数组a的索引值
b[i] = a[t]; //将随机索引对应的数组a的值依次赋给数组b
}
a: for (int i = 0; i < b.length - 1; i++) {
for (int j = i + 1; j < b.length; j++) {
if (b[i] == b[j]) { //循环遍历,若数组b中的值有相同的,就退出遍历,重新给数组b赋值
break a;
} else if (i == b.length - 2 && b[i] != b[j]) {
break b; //若数组b中没有相同的值,就退出总循环
}
}
}
}
for (int i = 0; i < b.length; i++) { //遍历打印数组b
System.out.println(b[i]);
}