java 生成10个从0到20的非重复随机整数[重复]

zhte4eai  于 2023-01-15  发布在  Java
关注(0)|答案(3)|浏览(175)
    • 此问题在此处已有答案**:

Creating random numbers with no duplicates(20个答案)
Generating 10 random numbers without duplicate with fundamental techniques(10个答案)
How to generate random numbers from 0 to 100 without duplicates when user enters the size of the array in Java?(5个答案)
6小时前关门了。
我在生成非重复的数字时遇到了问题。我尝试执行do-while循环,但似乎不起作用。我该如何解决它?

import java.util.Arrays;

public class Assignment2_Q2 {
    
    public static void main (String[] args){
        
        int[] myList = new int[10];
        
        number(myList);
        sortedOrder(myList);
        display (myList);
    }
        
    public static void number(int[] list){
            
        int random;
        
        random = (int)(Math.random() * 21);
        list[0] = random;
            
        for (int i = 1; i < list.length; i++){
            do{
                random = (int)(Math.random() * 21);
                list[i] = random;        
            }while(list[i] == list[i-1]);
        }
    }
    
    public static void sortedOrder(int[] list){
        
        java.util.Arrays.sort(list);    
    }
    
    public static void display(int[] list){
        
        System.out.println("The array in the sorted order:\n" + Arrays.toString(list) + "\n");  
    }             
}

输出示例:

The array in the sorted order:
[0, 0, 6, 7, 13, 16, 16, 18, 19, 20]

如你所见,0和16各出现两次。它们是重复的。我还看到一个数字在一次运行中出现三次。

jjjwad0x

jjjwad0x1#

生成一个数字1-20的列表,然后打乱列表,然后取前10个。

List<Integer> nums = IntStream.rangeClosed(1, 20).boxed().collect(toList());
Collections.shuffle(nums);
nums = nums.subList(0, 10);
72qzrwbm

72qzrwbm2#

您的问题出在while(list[i] == list[i-1])中这不是检查列表中是否包含您生成的随机数,而是检查最后生成的两个数字是否相同您不是检查前面的数字是否匹配,正确的方法是:

for (int i = 0; i < list.length; i++){
    bool found = false;
    do{
        random = (int)(Math.random() * 21);
         for(int j=0; j<i; j++) {
            if(list[j] == random) {
               found = true;
            }
        }
    }while(found = false);
    list[i] = random;
}
ygya80vv

ygya80vv3#

public static void main(String[] args) {
    int[] myList = new int[10];

    number(myList);
}

public static void number(int[] list) {
    int random;
    Set<Integer> used = new HashSet<>();

    for (int i = 0; i < list.length; i++) {
        do {
            random = (int) (Math.random() * 21);
        } while (used.contains(random)); // check if the number has been used before

        list[i] = random;
        used.add(random);
    }
}

相关问题