gpt4 book ai didi

java - 如何生成4个没有重复数字的随机数

转载 作者:行者123 更新时间:2023-12-04 10:46:45 25 4
gpt4 key购买 nike

我想生成 4 随机数,它们不能有重复的数字。

例如 4567 ,(它没有像 4557 这样的重复值)。

我希望它们是 随机

有没有办法实现这一目标?

最佳答案

我现在沉迷于流。但是流很慢。为了显示我写了以下主要方法的缓慢。 “generateWithLoop”方法涵盖了@WJS 的答案。

    public static void main(String[] args) {

long nanoStart = System.nanoTime();
generateWithStreams();
long nanoEnd = System.nanoTime();
System.out.println("Elapsed time with Streams : " + (nanoEnd - nanoStart) + " nano seconds");

nanoStart = System.nanoTime();
generateWithLoop();
nanoEnd = System.nanoTime();
System.out.println("Elapsed time with Loop : " + (nanoEnd - nanoStart) + " nano seconds");
}
控制台输出:

Elapsed time with Streams : 81367089 nano seconds

Elapsed time with Loop : 75093 nano seconds


随着流:
    public static void generateWithStreams() {

List<Integer> orderedList = getOrderedList();

for (int i = 0; i < 4; i++) {
List<Integer> shuffledList = getShuffledList(orderedList);
System.out.println(get4DigitNumber(shuffledList));
}

}

public static List<Integer> getOrderedList() {
return IntStream.range(0, 10).boxed().collect(Collectors.toList());
}

public static List<Integer> getShuffledList(List<Integer> list) {
return list.stream().sorted((o1, o2) -> ThreadLocalRandom.current().nextInt(-1, 2)).collect(Collectors.toList());
}

public static Integer get4DigitNumber(List<Integer> shuffledList) {
final Integer LIMIT = shuffledList.get(0).equals(0) ? 5 : 4;
return shuffledList.stream().limit(LIMIT).reduce(0, (sum, current) -> sum * 10 + current);
}
带循环:
    public static void generateWithLoop() {
Random r = new Random();
for (int k = 0; k < 4; k++) {
int val = gen(r);
System.out.println(val);
}

}

static int[] base = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

public static int gen(Random r) {
int val = 0;
int s = 10;
for (int i = 0; i < 4; i++) {
int n = r.nextInt(s);
val = val * 10 + base[n];
int save = base[n];
base[n] = base[--s];
base[s] = save;
}
return val < 1000 ? val * 10 + base[r.nextInt(s)] : val;
}

关于java - 如何生成4个没有重复数字的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59671114/

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