本文介绍了Java从数字间隔生成随机唯一数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个间隔中生成随机的唯一整数,但是应用程序冻结(无限循环).

I want to generate random unique int numbers from an interval but the app freezes out (infinite loop).

int[] ids = new int[200];
for(int i = 0; i < ids.length; i++){
   int temp = getUnique(ids);
   ids[i] = temp;
}

private int getUnique(int[] ids){
   while(true){
      int iRand = random(0, ids.length);
      if( unique( ids, iRand ) ) return iRand;
   }
}

private boolean unique(int[] arr, int i){
    for(int k : arr){
        if(k == i) return false;
    }

    return true;
}

private int random(int Min, int Max){
   return Min + (int)(Math.random() * ((Max - Min) + 1));
}

我想要一个0到200之间的整数数组,它们是随机排序的.我不知道为什么,但是应用程序冻结了.为什么?问题出在哪里?

I would like to have an array of integers between 0 - 200 sorted randomly. I don't know why, but the application is freezing out. Why? Where is the problem?

推荐答案

考虑使用将列表随机化.

例如:

Integer[] ids = getArrayOfNumbers();
List<Integer> idList = Arrays.asList(ids);
Collections.shuffle(idList);
ids = idList.toArray(ids);

这篇关于Java从数字间隔生成随机唯一数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:16
查看更多