如标题,用java噢
------解决方案--------------------------------------------------------
Random是java.util包下的
- Java code
Random random = new Random();static Map tmp = new HashMap();public static int generate() { int i = random.nextInt(100000); try { return tmp.get(i) == null ? generate() : i; } finally { tmp.put(i, ""); }}
------解决方案--------------------------------------------------------
Random rand= new Random();
Set<Integer> set= new HashSet<Integer>();
while (set.size() < 3)
set.add(rand.nextInt(30));
------解决方案--------------------------------------------------------
- Java code
int[] array = {0,1,2,3,4,5,6,7,8,9}; Random rand = new Random(); for (int i = 10; i > 1; i--) { int index = rand.nextInt(i); int tmp = array[index]; array[index] = array[i - 1]; array[i - 1] = tmp; } int result = 0; for(int i = 0; i < 6; i++) result = result * 10 + array[i]; System.out.println(result);
------解决方案--------------------------------------------------------
public class RandomUtils
{
private static String[] randomValues = new String[]{"0","1","2","3","4","5","6","7","8","9",
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","u",
"t","s","o","x","v","p","q","r","w","y","z"};
public static String getUsername(int lenght)
{
StringBuffer str = new StringBuffer();
for(int i = 0;i < lenght; i++)
{
Double number=Math.random()*(randomValues.length-1);
str.append(randomValues[number.intValue()]);
}
return str.toString();
}
public static void main(String[] args)
{
System.out.println(RandomUtils.getUsername(6));
}
}
这样就能随机生成六个不同的数了
------解决方案--------------------------------------------------------
不是都说了将曾经生成过的6位数放入HashSet中,随机生成一个数时先判断这个Set中是否存在,如果存在重新再生成一个新的随机数
- Java code
Set<Integer> set = new HashSet<Integer>();Random rand = new Random();for(int i = 0; i < 10000; i++) while(!set.add(rand.nextInt(900000) + 100000));
------解决方案--------------------------------------------------------
public void general2(){
List<Integer> list = new ArrayList<Integer>();
Random random = new Random();
while (true) {
int randomNum = random.nextInt(10);
boolean flag = false;
for(Integer in : list){
if(in == randomNum){
flag = true;
break;
}
}
if(!flag){
list.add(randomNum);
}
if(list.size()>=6){
break;
}
}
String randomStr = "";
for (Integer in : list) {
randomStr += in.toString();
}
System.out.println(randomStr);
}
6位不同的随机数