编程题:
写一个彩票的生成代码
要求:1-8随机选7个不重复的数字
提示:用数组保存7个数字,所有数字与以前的数字比较,如有重复重新生成
//方法一,在多数中选多数,效率较低,多数中选少则可用
import java.util.Random;
public class CaiPiao{
public static void main(String[] args){
int[] res = new int[7];
Random r = new Random();
for(int i = 0;i < res.length; i++){
res[i] = r.nextInt(8)+1;
for(int j = 0;j < i;j++){
if(res[i] == res[j]){
i--;
break;
}
}
}
for(int i = 0;i < res.length;i++){
System.out.print(res[i]+" ");
}
System.out.print('\n');
}
}
//方法二适合多数中选多数,如在10000中选出9999个不同的数
import java.util.Random;
public class CaiPiao{
public static void main(String[] args){
int[] res = new int[7];
int[] temp = {1,2,3,4,5,6,7,8,};
Random r = new Random();
for(int i = 0;i < res.length; i++){
int index = r.nextInt(temp.length-i);
res[i] = temp[index];
temp[index] = temp[temp.length-i-1];
}
for(int i = 0;i < res.length;i++){
System.out.print(res[i]+" ");
}
System.out.print('\n');
}
}
//方法三,导入HashSet类
import java.util.Random;
import java.util.HashSet; //自己会过滤重复的集合,它本身是运算
public class CaiPiao{
public static void main(String[] args){
HashSet hs = new HashSet();
Random r = new Random();
for(;;){
int temp = r.nextInt(8)+1;
hs.add(temp+"");
if(hs.size()==7) break;
}
System.out.println(hs);
}
}
//方法四,利用ArrayList
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Caipiao {
public static void main(String[] args) {
List<Integer> t = new ArrayList<Integer>();
Random r = new Random();
while (t.size() < 7) {
int x = r.nextInt(33) + 1;
if (!t.contains(x)) {
t.add(x);
}
}
for (int i = 0; i < t.size(); i++) {
System.out.print(t.get(i) + " ");
}
}
}