我已经制作了一个随机摔跤比赛发生器,我从教科书的随机短语发生器中进行了改编。我想知道如何制作它,所以同一个名字在同一次运行中没有完成两次。没有The Crusher vs. The Crusher,对吧?
public class matchOMatic {
public static void main (String [] args) {
String [] wordListOne = {"The Crusher", "The Main Man", "The Macho-man, Randy Savage", "The Nature Boy, Rick Flare", "Batista", "Hollywood Hulk Hogan", "Vader", "The Undertaker", "Stone Cold Steve Austin" };
String [] wordListThree = {"The Crusher", "The Main Man", "The Macho-man, Randy Savage", "The Nature Boy, Rick Flare", "Batista", "Hollywood Hulk Hogan", "Vader", "The Undertaker", "Stone Cold Steve Austin"};
int oneLength = wordListOne.length;
int threeLength = wordListThree.length;
int rand1 = (int) (Math.random() * oneLength);
int rand3 = (int) (Math.random() * threeLength);
String phrase = wordListOne[rand1] + " and in the opposite corner is his opponent, " + wordListThree[rand3];
System.out.print("In this corner we have " + phrase);
System.out.println("!");
}
}
答案 0 :(得分:2)
非常简单的解决方案!
在为rand3和rand2:
提供值之后,请将其放入while(rand3 == rand1) {
rand3 = (int) (Math.random() * threeLength);
}
这将继续为rand3选择一个新值,直到值不同为止!
我希望这会有所帮助。祝你的计划好运:))
答案 1 :(得分:1)
最干净的解决方案是将名称存储在ArrayList
而不是字符串数组中,shuffle列表,并成对迭代以创建匹配。混洗长度为N的列表是O(N),并且保证不会在预定的匹配中产生重复。
答案 2 :(得分:0)
如果随机结果相同,你可以选择下一个(或前一个)。
if ( rand3 == rand1 )
rand3 = (rand3 +1) % threeLength
编辑: 如下所述,这会产生不好的偏见。
其他可能的解决方案是不要在下一个随机滚动中包含第一个随机选择的索引
// -1 because we are not including the same pick
int rand3 = (int) (Math.random() * ( threeLength-1) );
// fix the index because we haven't actually removed it from the array
if (rand3 >= rand1)
rand3 = (rand3 +1) % threeLength