---
title: "简单的不重复随机数生成"
author: "dragonhunter"
date: "2016-11-25T12:06:05Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2016-11-28T10:18:15Z"
id: 2341036
url: "https://dragonhunter.iteye.com/blog/2341036"
---

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&lt;Integer,char\[]&gt; 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 &gt; array.length){  
            throw  new RuntimeException("total is too big , must &lt;="+array.length);  
        }  
        char\[] seq = array;  
        char\[] output = new char\[total];  
        Random random = new Random();  
        int end = array.length - 1;  
        for (int i = 0; i &lt; 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 &lt; total;i++){  
            sb.append(output\[i]);  
        }  
        return sb.toString();  
    }  
}