[英]How do I compare results from different loops with each other?
我的问题是,使用我现在拥有的代码,它不断生成新的结果/骰子,但是说第 2 轮中的 result2 与第 3 轮中的 result1 相同,那么它也应该停止生成新结果。 现在不这样做了。 我怎么能调整它呢?
int trials = 0;
for (int totalGames = 1; totalGames <= 3; totalGames++ ) {
int result1, result2;
// simulating dice rolls
do {
result1 = (int) (Math.random() * 6) + 1;
result2 = (int) (Math.random() * 6) + 1;
trials++;
System.out.println(result1);
System.out.println(result2);
}
while (result1 != result2);
您必须跟踪某种集合中的每个结果,然后检查结果是否已包含在该集合中:
/**
* @return The amount of trials it took to get two matching numbers.
*/
public static int roleDice() {
int trials = 0;
HashSet<Integer> seenResults = new HashSet<Integer>();
for (int totalGames = 1; totalGames <= 3; totalGames++) {
int result1, result2;
do {
result1 = (int) (Math.random() * 6) + 1;
result2 = (int) (Math.random() * 6) + 1;
System.out.println(result1);
System.out.println(result2);
// Set.add(...) returns false if the value is already contained
if (!(seenResults.add(result1) && seenResults.add(result2)))
return trials;
trials++;
} while (result1 != result2);
}
return trials;
}
public static void main(String[] args) {
int trials = roleDice();
}
通过这种方式,您可以在每次迭代中检查先前的 result1 值是否与当前的 result2 值匹配,以及先前的 result2 值是否与当前的 result1 值匹配,直到条件评估为 true 并退出 while 循环。
int trials = 0;
for (int totalGames = 1; totalGames <= 3; totalGames++) {
Set<Integer> result1Set = new HashSet<>();
Set<Integer> result2Set = new HashSet<>();
while (true) {
trials++;
int result1 = (int) (Math.random() * 6) + 1;
int result2 = (int) (Math.random() * 6) + 1;
if (result1Set.contains(result2) || result2Set.contains(result1)) {
break;
}
result1Set.add(result1);
result2Set.add(result2);
System.out.println(result1);
System.out.println(result2);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.