生成不重复的随机数
- package com.mycompany.test;
- import java.util.HashSet;
- import java.util.Random;
- import java.util.Set;
- public class Test1 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Set<String> set = cDifferentRandoms(100000, 11); // 产生100000个长度为11的随机无重复字符串
- long startTime = System.currentTimeMillis();
- for (String str : set) {
- System.out.println(str);
- }
- long endTime = System.currentTimeMillis();
- System.out.println("Totally " + ((float)(endTime - startTime) / 1000) + " seconds used!");
- }
- public static Set<String> cDifferentRandoms(int n, int m) { // 产生n个只含有数字和字母长度为m(m<=52)的无重复随机字符串
- if (m > 52) {
- return null;
- } else {
- Set<String> set = new HashSet<String>();
- while (set.size() < n) {
- set.add(cRandom(m));
- }
- return set;
- }
- }
- public static String cRandom(int m) { // 产生1个长度为m只含有字母的随机字符串
- char[] chs = new char[m];
- for (int i = 0; i < m; i++) {
- chs[i] = cNumOrCharRandom();
- }
- return new String(chs);
- }
- public static char cNumOrCharRandom() { // 产生一个随机数字或字母
- String temp = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
- return (char) temp.charAt(iRandom(0, 61));
- }
- public static int iRandom(int m, int n) { // 产生一个[m,n)之间的随机整数
- Random random = new Random();
- int small = m > n ? n : m;
- int big = m <= n ? n : m;
- return small + random.nextInt(big - small);
- }
- }