简单的不重复随机数生成

阅读更多

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class RandomUtil {
    public static char[] lower = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    public static char[] upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    public static char[] num = "0123456789".toCharArray();
    public static char[] letter = org.apache.commons.lang.ArrayUtils.addAll(lower,upper);
    public static char[] all = org.apache.commons.lang.ArrayUtils.addAll(letter,num);

    public static int LOWER_TYPE = 0;
    public static int UPPER_TYPE = 1;
    public static int NUMBER_TYPE = 2;
    public static int LETTER_TYPE = 3;
    public static int ALL_TYPE = 4;
    public static Map map = new HashMap(){{
        put(LOWER_TYPE,lower);
        put(UPPER_TYPE,upper);
        put(NUMBER_TYPE,num);
        put(LETTER_TYPE,letter);
        put(ALL_TYPE,all);
    }};

    public static void main(String[] args) {
        System.out.println(RandomUtil.randomNoRepeatString(44, ALL_TYPE));
        System.out.println("finish");
    }

    public static String randomNoRepeatString(int total,int type){
        Object o = map.get(type);
        char[] array = (char[])o;
        if(array == null){
            throw new RuntimeException("type is error");
        }
        if(total > array.length){
            throw  new RuntimeException("total is too big , must <="+array.length);
        }
        char[] seq = array;
        char[] output = new char[total];
        Random random = new Random();
        int end = array.length - 1;
        for (int i = 0; i < total; i++)
        {
            int num = random.nextInt(end + 1);
            output[i] = seq[num];
            seq[num] = seq[end];
            end--;
        }
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i < total;i++){
            sb.append(output[i]);
        }
        return sb.toString();
    }
}

你可能感兴趣的:(不重复随机数生成)