35选7 问题 要求随机出来7个数 不能有重复 下面是我用7个数做的测试 结果是有重复的
想到脑袋大也没想到为啥会出现重复的 麻烦各位来帮找找错误
思路是这样:每随机出来一个数 就打印 然后把这个数用数组的最后一个数替换掉 然后继续执行
小弟谢谢各位啦~~~~public class Ticket { public static void main(String[] args) {
int[] pool = new int[7];
int[] result = new int[7];
int temp = 0;
for (int i = 0; i < pool.length; i++) {
pool[i] = i + 1;
}
for (int j = 0; j < result.length; j++) {
result[j] = pool[(int) (Math.floor(Math.random() * (6 - j)))];
pool[(result[j] - 1)] = pool[(pool.length - 1 - j)]; System.out.print(result[j] + " ");
} }}
想到脑袋大也没想到为啥会出现重复的 麻烦各位来帮找找错误
思路是这样:每随机出来一个数 就打印 然后把这个数用数组的最后一个数替换掉 然后继续执行
小弟谢谢各位啦~~~~public class Ticket { public static void main(String[] args) {
int[] pool = new int[7];
int[] result = new int[7];
int temp = 0;
for (int i = 0; i < pool.length; i++) {
pool[i] = i + 1;
}
for (int j = 0; j < result.length; j++) {
result[j] = pool[(int) (Math.floor(Math.random() * (6 - j)))];
pool[(result[j] - 1)] = pool[(pool.length - 1 - j)]; System.out.print(result[j] + " ");
} }}
result[j] = pool[(int) (Math.floor(Math.random() * (6 - j)))];//这样获取有重复很正常pool[(result[j] - 1)] = pool[(pool.length - 1 - j)];//你这句是干什么的,没作用System.out.print(result[j] + " ");不知道楼主啥子意思!
这样就不会重复出现了 覆盖之后 让原数组的长度减去一 就是 pool[(int) (Math.floor(Math.random() * (6 - j)))]; 这用句话实现
破图!
是不是你最后一句打印写错了//System.out.print(result[j] + " ");
System.out.print(pool[j] + " ");//是不是改成这样
for (int i : getLotteryArr()) {
System.out.printf("%d ", i);
}
}
public static int[] getLotteryArr(){
int[] result = new int[7];
int[] num = new int[35];
for (int i = 0; i < num.length; i++) {
num[i] = i + 1;
}
Random random = new Random();
int index;
for (int i = 0; i < result.length; i++) {
index = random.nextInt(34 - i) + 1;
result[i] = num[index];
num[34 - i] ^= num[index];
num[index] ^= num[34 - i];
num[34 - i] ^= num[index];
}
return result;
}
}
public static void main(String[] args) {
List<Integer> pool = new ArrayList<Integer>();
int[] result = new int[7];
for (int i = 0; i < 35; i++) {
pool.add(i + 1);
}
for (int j = 0; j < result.length; j++) {
Random rand = new Random();
result[j] = pool.remove(Math.abs((rand.nextInt())) % (pool.size())); System.out.print(result[j] + " ");
}
}
int []arr=new int[35];
boolean []a=new boolean[35];
for(int i=0;i<35;i++){
arr[i]=i+1;
a[i]=false;
}
int m=0;
while(true){
int suiji=(int)(Math.random()*35);
if(a[suiji]==false){
System.out.print(arr[suiji]+" ");
a[suiji]=true;
m++;
}
if(m==8){break;}
}
} public static void main(String[] args) {
int []arr=new int[35];
boolean []a=new boolean[35];
for(int i=0;i<35;i++){
arr[i]=i+1;
a[i]=false;
}
int m=0;
while(true){
int suiji=(int)(Math.random()*35);
if(a[suiji]==false){
System.out.print(arr[suiji]+" ");
a[suiji]=true;
m++;
}
if(m==8){break;}
}
}