I think there is a misunderstanding here. It isn’t about whether random.nextInt(n) returns the same number twice, it’s perfectly fine if 1 ball is under the same cup in a few games in a row. It’s not fine when the program tells you that the ball is in cup 1 and 3 in the very same game.
[quote=“brollysan,post:28,topic:41487”]
The difference is that the way your code calls nextInt(…) results in the possibility that two or three booleans fields are set to true
, which is an incorrect state. My code will always leave exactly 1 ball in 3 cups, all the time, without any chance of an incorrect state. That we’re both using nextInt(n) and your implementation potentially causes the program to reach an invalid state, doesn’t mean that my code suffers from the same flaw.
[quote=“brollysan,post:28,topic:41487”]
Sigh. Oh well, here’s is the proof, not by obscure reasoning, but simply by bruteforcing your algorithm, and counting the number of times it reaches an invalid state:
Random r = new Random(123L);
int[] ballHistogram = new int[4];
for (int i = 0; i < 1000 * 1000; i++) {
int u = r.nextInt(3);
int v = r.nextInt(3);
int w = r.nextInt(3);
int[] a = new int[] {u, v, w};
boolean[] b = new boolean[] {false, false, false};
int m = Math.min(u, Math.min(v, w));
if (a[0] == m) {
b[0] = true;
}
if (a[1] == m) {
b[1] = true;
}
if (a[2] == m) {
b[2] = true;
}
// verify internal state
int ballCount = 0;
if (b[0]) {
ballCount++;
}
if (b[1]) {
ballCount++;
}
if (b[2]) {
ballCount++;
}
ballHistogram[ballCount]++;
}
System.out.println("total games: " + (ballHistogram[0] + ballHistogram[1] + ballHistogram[2] + ballHistogram[3]));
for (int i = 0; i < ballHistogram.length; i++) {
System.out.println("games with " + i + " balls in 3 cups: " + ballHistogram[i]);
}
Output:
total games: 1000000
games with 0 balls in 3 cups: 0
games with 1 balls in 3 cups: 555142
games with 2 balls in 3 cups: 333727
games with 3 balls in 3 cups: 111131
In short: over 44% of the games end up in an invalid state, a far cry from 1/Integer.MAX_VALUE, or the proposed 0.5% and 1.0%.
I hope this elaborate explaination brings JGO back to ‘StackOverflow quality’ :-*