java - 将新数组条目与其所有祖先进行比较

标签 java arrays loops random while-loop

我正在尝试创建一个由唯一随机整数组成的数组。我构建的方法(如下所示)几乎可以工作。问题出在 while 循环中,它将新的随机条目与其直接祖先进行比较。此条件确保数组中不会存在一对并排的匹配值。不幸的是,这个条件不会将新的随机值与迄今为止生成的每个随机值进行比较。我怎样才能做到这一点?

private static Random rand = new Random();

//'dynamicLength' is dependent on another object. With the way I've set up the 
//method, the size shouldn't matter.
private static int[] randArr = new int[dynamicLength];

public static int[] randGenArr(int upBound, int lowBound)
{
    int newRand;

    for (int i1 = 0; i1 < randArr.length; i1++)
    {
       //new random value
       newRand = rand.nextInt(upBound - lowBound + 1) + lowBound;

       //walk through the randArr up to the point we initialized
       //last iteration
       for (int i2 = 0; i2 <= i1; i2++)
       {
           //compare the new value to its IMMEDIATE ancestor
           while (newRand == randArr[i2])
           {
               newRand = rand.nextInt(upBound - lowBound + 1) + lowBound;
           }
       } 
       //after validation, initialize randArr          
       randArr[i1] = newRand;
   }

   return randArr;
}

我只关注这段代码的主体。我已经包含了方法 header 和 为了清晰起见,字段声明。

最佳答案

Set 是跟踪独特项目的好工具。您可以使用 set 来生成随机数,并且仅在最后返回数组。

Integer[] randNumbers(int amount, int lower, int upper) {
    Set<Integer> result = new HashSet<>();
    while(result.size() < amount) {             //try until there are enough numbers in result
         result.add( /*generate new number*/);  //add only unique number to result
    }
    return result.toArray(new Integer[amount]); //converts Set to array
}

关于java - 将新数组条目与其所有祖先进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38596880/

相关文章:

java - Spring Security 和自定义身份验证提供程序

sql - 匹配 SQL/BigQuery 中相同索引的数组元素

java - context.xml 和 server.xml 之间的区别?

java - 如何在 java 中增加 Netbeans 平台应用程序的堆内存?

java - 二维数组的第一个索引在没有任何显式增量的情况下增加

java - 为什么要乘而不是求和

c - 循环改变不在循环内部的字符串?

c++ - 需要左值作为赋值的左操作数(while 循环)

html - 表、TR各2循环、PHP、HTML

java - 修改滚动日志文件名以在 log4j 中包含日期