Skip to content

Instantly share code, notes, and snippets.

@ryanmjacobs
Created November 20, 2016 07:47
Show Gist options
  • Save ryanmjacobs/8710495f910c1084c617381bf91551ef to your computer and use it in GitHub Desktop.
Save ryanmjacobs/8710495f910c1084c617381bf91551ef to your computer and use it in GitHub Desktop.
import java.util.Random;
public class RollSimulation {
public static void main(String[] args) {
Random rand = new Random();
for (int f = 1; f <= 6; f++) {
int[] rolls1 = new int[8];
int[] rolls2 = new int[8];
// use both methods to generate rolls, one million iterations each
for (int i = 0; i < 1e5; i++) {
rolls1[nextRoll1(f, rand)]++;
rolls2[nextRoll2(f, rand)]++;
}
// print out method 1
System.out.print("r1 f=" + f + ", ");
for (int i = 1; i <= 6; i++) {
double prob = rolls1[i]/1e5*100;
System.out.printf("%d: %s%.2f%%", i, prob == 0 ? " " : "", prob);
System.out.print(i == 6 ? "\n" : " ");
}
// print out method 2
System.out.print("r2 f=" + f + ", ");
for (int i = 1; i <= 6; i++) {
double prob = rolls2[i]/1e5*100;
System.out.printf("%d: %s%.2f%%", i, prob == 0 ? " " : "", prob);
System.out.print(i == 6 ? "\n" : " ");
}
System.out.print("\n");
}
}
public static int nextRoll1(int forbidden, Random rand) {
int r = rand.nextInt (5) + 1;
if (r >= forbidden)
r = r + 1;
return r;
}
public static int nextRoll2 (int forbidden, Random rand) {
int r = rand.nextInt (6) + 1;
while (r == forbidden)
r = rand.nextInt (6) + 1;
return r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment