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

产生无重复的随机数
希望从10个数字0-9和26上字母A-Z中产生无重复的8位随机数,如何产生?

------解决方案--------------------
char[] c={ '0 ', '1 ', '2 ', '3 '...... 'Z '};
boolean[] used=new boolean[36];

char[] result=new char[8];
for(int i=0;i <result.legnth;i++)
{
int random;//0~36的随机数
while(used[random=(...)]);
used[random]=true;
result[i]=c[random];
}
String 8位无重复字符串=new String(result);
------解决方案--------------------
import java.math.*;
import java.util.*;
class test2 {
static char[] result=new char[8];
static char[] c=

{ '0 ', '1 ', '2 ', '3 ', '4 ', '5 ', '6 ', '7 ', '8 ', '9 ', 'A ', 'B ', 'C ', 'D ', 'E ', 'F ', 'G ', 'H ', 'I ', 'J ', 'K ', 'L ', 'M '

, 'N ', 'O ', 'P ', 'Q ', 'R ', 'S ', 'T ', 'U ', 'V ', 'W ', 'X ', 'Y ', 'Z '};
public static void main(String arg[]) {
randoms();
String s=new String(result);
System.out.println(s);
}
public static void randoms()
{
Random r = new Random();

int temp1;
char temp2;
int len = c.length;
for(int i=0;i <8;i++)
{
temp1 = Math.abs(r.nextInt())% len;
result[i] = c[temp1];
temp2 = c[temp1];
c[temp1] = c[len-1];
c[len-1] = temp2;
len--;
}
}
}