日期:2014-05-20  浏览次数:20756 次

在线等:产生不重复的52个随即数,已经附了源代码,一运行机器慢的就要死,
import java.util.Arrays;
import java.util.Random;

public class BasicDebug {
public static void main(String[] args) {
//用于保存产生的随机数是否已用
boolean[] isExist = new boolean[52];
Random r = new Random();
//存储不重复0-51之间的随机数
int[] card = new int[52];
//保存产生的随机数
int temp;
int count = 0;
boolean flag = false;
while (count < 52) {
temp = r.nextInt(52);
flag=false;
//判读产生的随机数是否已经存在了
for (int i = 0; i < 52; i++) {
if (isExist[i]) {
flag = true;
//如果已经找到就不用继续找了
break;
}
}
//产生的随即数已经存在,将进入下一循环
if(flag) continue;
//将产生的随机数,设为已经存在
isExist[temp] = true;
card[count++] = temp;
System.out.print(temp + "\t");
}
System.out.println();
//为了清楚的显示产生的随机数,进行了排序
Arrays.sort(card);
for (int j : card) {
System.out.print(j + "\t");
}
}
}


------解决方案--------------------
import java.util.Arrays;
import java.util.Random;

public class BasicDebug {
public static void main(String[] args) {
// 用于保存产生的随机数是否已用
boolean[] isExist = new boolean[52];
Random r = new Random();
// 存储不重复0-51之间的随机数
int[] card = new int[52];
// 保存产生的随机数
int temp;
int count = 0;
while (count < 52) {
temp = r.nextInt(52);
// 判读产生的随机数是否已经存在了,产生的随即数已经存在,将进入下一循环
if (isExist[temp]) continue;
//将产生的随机数,设为已经存在 
isExist[temp] = true;
card[count++] = temp;
System.out.print(temp + "\t");
}
System.out.println();
//为了清楚的显示产生的随机数,进行了排序 
Arrays.sort(card);
for (int j : card) {
System.out.print(j + "\t");
}
}
}