gpt4 book ai didi

java - 有条件地生成 10 个随机对

转载 作者:行者123 更新时间:2023-11-29 08:35:38 24 4
gpt4 key购买 nike

我有以下 for 循环,它应该生成两个随机整数并调用 grid.place(x,y)。如果 grid.place(x,y) 返回 false,我想弄清楚如何生成不同的对。如果提供的 x 和 y 之前未提供,则 place 方法返回 true。谢谢。

for (int i = 0; i < 10; i++) {
mx = randomGenerator.nextInt(10);
my = randomGenerator.nextInt(10);
grid.place(mx,my);
}

最佳答案

这是 do-while 循环的完美情况:

for (int i = 0; i < 10; i++) {
do{
mx = randomGenerator.nextInt(10);
my = randomGenerator.nextInt(10);
}while(!grid.place(mx,my));

}

另一种解决方案是使用 Collections.shuffle() 方法。像这样:

List<Integer> xPos = IntStream.rangeClosed(0,10).boxed().collect(Collectors.toList());
List<Integer> yPos = IntStream.rangeClosed(0,10).boxed().collect(Collectors.toList());

Collections.shuffle(xPos);
Collections.shuffle(yPos);


for(int i=0;i<10;i++)
grid.place(xPos.get(i), yPos.get(i));

这将为您提供所有坐标,并且永远不会比 do-while 循环更复杂地重复

关于java - 有条件地生成 10 个随机对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44292048/

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