gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:03:40 26 4
gpt4 key购买 nike

我正在尝试创建一个由唯一随机整数组成的数组。我构建的方法(如下所示)几乎可以工作。问题出在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com