繁体   English   中英

如何生成某个范围内的随机数列表,然后获取未包含在该列表中的数字

[英]How to generate a list of random numbers between a certain range, then get numbers not included in that list

我生成了一个包含 1 到 300 之间的 20 个唯一随机数的列表,并将其用于我需要使用它的目的。 但是,我还需要将未添加到列表中的数字添加到另一个列表中,以便在另一个函数中使用。

这是我用来生成 20 个数字的随机列表的代码:

JToggleButton[][] p = new JToggleButton[5][4];
ArrayList<Integer> list = new ArrayList<Integer>();

    Random rand = new Random();
    for (int i = 0; i < p.length; i++) {
        for (int j = 0; j < p[i].length; j++) {

            int randomNum = rand.nextInt((300 - 1) + 1) + 1;

            while (list.contains(randomNum)) {
                randomNum = rand.nextInt((300 - 1) + 1) + 1;
            }

            list.add(randomNum);

// rest of code that I need the random number list for

我需要将这 20 个项目列表中未包含的其他 280 个数字放入另一个列表中,但我不确定如何实际获取这些“未使用”的数字

如果你真的像你说的那样需要两个列表,那么这里有一种方法:

final int numberOfInts = 300;
List<Integer> excluded = new ArrayList<>();
for (int i = 1; i <= numberOfInts ; i++) {
    excluded.add(i);
}

Random rand = new Random();
List<Integer> included = new ArrayList();
for (int i = 0; i < p.length; i++) {
    included.add(excluded.remove(rand.nextInt(excluded.size())));
}

我花了很长时间才明白你的问题在问什么。

    ArrayList<Integer> otherNumbers = new ArrayList<Integer>();
    for(int x = 0; x < list.size(); x++) {
        if(!list.contains(x+1)) {
            otherNumbers.add(x+1);
        }
    }

您可以通过跳过 20 个数字列表包含的值来填充新列表。

我认为最好的方法是生成一个单独的列表并用 1 到 300 之间的每个数字填充它。之后,只需遍历生成的随机数列表并从 1 到 300 列表中删除这些元素。 像这样的东西..

ArrayList<Integer> list300 = new ArrayList<Integer>();
For (int i = 1; i <= 300; i++) {
    list300.add(i);
}

For (int i = 0; i < list.size(); i++) {
    if (list300.contains(list[i])) {
        list300.remove(Integer.vaueOf(list[i]));
    }
}

您可以创建一个包含所有 300 个数字的List ,然后当您向另一个列表添加一个随机数时,只需从List删除具有所有值的相同数字:

创建列表:

    ArrayList<Integer> excludedNumbers = new ArrayList<>(300);
    for (int i = 1; i <= 300; i++){
        excludedNumbers.add(i);
    }

在当前代码中添加一行:

ArrayList<Integer> randomList = new ArrayList<>();
Random rand = new Random();

for (int i = 0; i < p.length; i++) {
    for (int i = 0; i < p[i].length; i++) {

            int randomNum = rand.nextInt((300 - 1) + 1) + 1;

            while (randomList.contains(randomNum)) {
                randomNum = rand.nextInt((300 - 1) + 1) + 1;
            }

            excludedNumbers.remove((Integer) randomNum); // the new line
            randomList.add(randomNum);
    }
} 

Integer确保List使用Object remove 函数而不是int remove 选项。

我希望我答对了你的问题,因为这对我来说有点难以理解。 我会这样做:

ArrayList<Integer> notIncludedNumbers = new ArrayList<Integer>();
for (int i = 0; i <= 300; i++){
   if (!list.contains(i))
      notIncludedNumbers.add(i);
}

您迭代从 1 到 300 的所有数字,如果它们不包含在您的列表中,并且带有 20 个随机数,则将它们添加到notIncludedNumbers列表中。 我希望我能帮上忙。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM