java - 将不重复的数字存储在数组中

标签 java arrays random boolean

概述: 我的程序必须在数组中存储 20 个从 1 到 100 范围内随机生成的非重复数字。 问题: 如果我在内部 for 循环中找到匹配项(重复的 #),我会标记 boolean 变量。这是我不知道该怎么做。在 for 循环之后,如果 boolean 值尚未被标记,我想将随机数添加到数组中。我还想增加 x(直到存储了 20 个不重复的数字),但前提是我将元素添加到数组中。

public void duplication(){
    int max = 100; // max value for range
    int min = 1; // min value for range
    boolean duplicate = false;
    Random rand = new Random();

    for (int x = 0; x < 20; x++){
        //initiates array that stores 20 values
        int[] all = new int[20];
        //generates # from 1-100
        int randomNum = rand.nextInt((max - min) + 1) + min;
        all[x] = randomNum;
        //iterates through array
        for (int i : all) {
            //if there's a match (duplicate) flag boolean
            if (i == randomNum){
                duplicate = true;
            }
            else {
                duplicate = false;
            }
        }
    }
    //if boolean hasn't been flagged
    if (duplicate=false){
        //store to array
    }
}   

最佳答案

这将为您提供一个 0 到 100 之间的随机整数数组

public static void main(String[] args) {
    Set<Integer> s = new HashSet<Integer>(); // create a set
    Random r = new Random();
    while (s.size() < 20) {
        s.add(r.nextInt(100)+1);  // add elements to set upto size =20
    }
    Integer[] array = new Integer[20];
    s.toArray(array); // convert set to array of Integers
    System.out.println(Arrays.toString(array));

}

操作:

[68, 69, 64, 65, 66, 67, 47, 74, 14, 17, 16, 21, 81, 54, 52, 82, 59, 57, 63, 88]

关于java - 将不重复的数字存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28275607/

相关文章:

python - 在python中生成固定长度的随机字符串列表

java - 在java中的for循环之外打印i的值

java - 相同的方法调用,LinkedList、Queue 与 List 中的不同结果

java - 尽管使用了 -Xmx 堆选项,为什么 Cassandra 仍占用这么多内存?

java - 多维数组画图

javascript - 我如何将对象数组与下划线js合并

java - 是否有谷歌API来验证Java中的gmail是否有效?

ruby - 将数组中的每个数组相交 - Ruby

java - 如何优化我的代码以在 Java 中高速生成伪随机字符串?

java - 跨版本和平台的一致随机数