生成不重复的随机数

package com.demo.sw.test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 
 * @author Mr.J
 *
 */
public class NoRepeatNums {
	
	public static void main(String[] args) {
		
		int [] arr = getNoRepeatNums(3,1,102);
		
		
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i]+" ");
		}
		
	}
	
	
	/**
	 * 从 from 到  to 取  n 个部重复的数
	 * @param n
	 * @param from
	 * @param to
	 * @return
	 */
	public static int[] getNoRepeatNums(int n, int from, int to){
		int fl = (from+"").length();
		int tl = (to+"").length();
		//int fmin = tl<fl?tl:fl;
		int tmax = tl>fl?tl:fl;
		int f = from<to?from:to;
		int t = from>to?from:to;
		if((t-f)<n){
			int []rtArr = new int [t-f+1] ;
			int it = 0;
			for (int i = f; i <= t; i++) {
				rtArr[it]= i;
				it++;
			}
			return rtArr;
		}

		//int min = Integer.parseInt(appendChar("1",'0',fmin));
		int max = Integer.parseInt(appendChar("1",'0',tmax));
		int num = -1;
		Set s = new HashSet();
		while(true){
			if(null !=s && s.size() >= n){
				break;
			}
			
			num = (int)(Math.random()*max);
			if(f<=num&&num<=t){
				if(!s.contains(num)){
					s.add(num);
				}
			}
			
		}
		
		int [] arr = new int[n];
		
		Iterator itr = s.iterator();
		int i = 0;
		while(itr.hasNext()){
			Integer in = (Integer)itr.next();
			arr[i] = in.intValue();
			i++;
		}
		
		return arr;
		
	}
	
	/**
	 * 在字符串 S 后追加  num 个 C 并返回
	 * @param s
	 * @param c
	 * @param num
	 * @return
	 */
	public static String appendChar(String s, char c, int num){
		for (int i = 0; i < num; i++) {
			s+=c;
		}
		return s;
	}
	
	
	/**
	 * 默认方法从 10 中取出 n 个部重复的数,n 必须小于或等于10 否则无法返回null
	 * @param n
	 * @return
	 */
	public static int[] getDefaultNoRepeatNums (int n) {
		if(n>10){
			return null;
		}
		
		Set s = new HashSet();
		while(true){
			if(null !=s && s.size() >= n){
				break;
			}
			
			int num = (int)(Math.random()*10);
			if(!s.contains(num)){
				s.add(num);
			}
		}
		
		int [] arr = new int[n];
		
		Iterator itr = s.iterator();
		int i = 0;
		while(itr.hasNext()){
			Integer in = (Integer)itr.next();
			arr[i] = in.intValue();
			i++;
		}
		
		return arr;
	}


}
posted @ 2011-03-18 23:12  标准小兵  阅读(224)  评论(0编辑  收藏  举报