gpt4 book ai didi

java - 生成具有 1 到 8 之间相同对的随机数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:04:15 25 4
gpt4 key购买 nike

就像我的问题一样,我需要生成在范围内具有相同对的随机数。我试图生成随机数并存储在一个数组中,但这些数字重复了两次以上。我要在范围内生成 16 个随机数。知道如何让它只生成相同的随机数对吗?

最佳答案

以下将完成我认为的工作:

import java.util.*;

class Randoms {
public static void main(String[] args) {
List<Integer> randoms = new ArrayList<Integer>();
Random randomizer = new Random();
for(int i = 0; i < 8; ) {
int r = randomizer.nextInt(8) + 1;
if(!randoms.contains(r)) {
randoms.add(r);
++i;
}
}
List<Integer> clonedList = new ArrayList<Integer>();
clonedList.addAll(randoms);
Collections.shuffle(clonedList);

int[][] cards = new int[8][];
for(int i = 0; i < 8; ++i) {
cards[i] = new int[]{ randoms.get(i), clonedList.get(i) };
}

for(int i = 0; i < 8; ++i) {
System.out.println(cards[i][0] + " " + cards[i][1]);
}
}
}

上面的一个示例运行给出:

1 2
8 6
4 3
3 7
2 8
6 1
5 5
7 4

希望对您有所帮助。

关于java - 生成具有 1 到 8 之间相同对的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2331364/

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