一种快速获取N个不同随机数的方法

     因为项目需要,需要写一个算法来获取在F范围内,获取N个不同的值的算法,因为random方法产生的值,是有可能存在相同的值,所以,选出来的值以后需要把相同的值去掉,因此根据这个思路,便有了以下的算法:

 

public static int[] randomInt(int n, int f) {
		int intRet[] = new int[n];
		int intRd = 0;
		int count = 0;
		
			while (count < n) {
			Random rdm = new Random(System.currentTimeMillis());
			intRd = rdm.nextInt(f);
			int flag = 0;
			for (int i = 0; i < count; i++) {
				if (intRet[i] == intRd) {					
					flag=1;
					break;					
				}			
			}
			if(flag==0){
				intRet[count]=intRd;
				count++;
			}
		}
		
		return intRet;
	}

    

     原理很简单,就是随机生成N个数,然后通过循环去掉相同的。但是这个算法效率很差,特别是要选取的数字的个数超过1000以后,这个算法几乎需要1、2秒。因此为了解决这个问题,我引入了HashSet。因为Set内是不允许存在相同的值的,于是利用这个特性,写出了这个算法。

 

public static int[] randomSet(int n, int f){
		Random rdm = new Random(System.currentTimeMillis());
		Set<Integer> intSet =  new HashSet<Integer>();
		
		while(intSet.size()<n){
			intSet.add(rdm.nextInt(f));			
		}
		
		
		int intRet[] = new int[n];
		Iterator<Integer> it = intSet.iterator();
		int i=0;
		while(it.hasNext()&i<n){
			intRet[i] = Integer.parseInt(it.next().toString());
			i++;						
		}
		
		return intRet;		
	}

 其实这个算法就是利用了Set的特性,去除相同的数值,而且这个算法效率非常高,特别是选取的数超过1000个的时候,效率可以比前面的算法提高上百倍。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值