gpt4 book ai didi

java - 当用户在Java中输入数组大小时,如何生成从0到100的随机数而不重复?

转载 作者:行者123 更新时间:2023-12-02 16:10:01 24 4
gpt4 key购买 nike

Write a program to generate any number of random integers in 0 to 100range. Your program should get the size as a parameter and return thenumbers as an array.

这是我得到的问题,下面是我试过的代码,但我得到了这段代码的重复。如何生成不重复的随机数?

    import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("size:\t");
int n = sc.nextInt();

int[] arr = new int[n];

Random rand = new Random(); //instance of a random class.
int upperbound = 101; //generate random values from 0-100

for(int i=0;i<n;i++) {
arr[i] = rand.nextInt(upperbound);
}
System.out.println("Random Numbers: "+ Arrays.toString(arr));

}
}

最佳答案

您可以创建一个包含从 0 到 100 的所有值的列表,然后将其打乱并提取该列表的前 n 个元素,如下所示:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("size:\t");
int n = sc.nextInt();

int bound = 100;

List<Integer> items = IntStream.range(0, bound + 1)
.boxed()
.collect(Collectors.toList());

Collections.shuffle(items);

int[] arr = new int[Math.min(n, bound + 1)];
for(int i = 0; i < arr.length; i++){
arr[i] = items.get(i);
}

System.out.println("Random Numbers: "+ Arrays.toString(arr));
}

关于java - 当用户在Java中输入数组大小时,如何生成从0到100的随机数而不重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68264509/

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