Created
September 9, 2017 11:33
-
-
Save LuxXx/e9aab4375962e59581a5ceea57af4d64 to your computer and use it in GitHub Desktop.
A dice game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.PriorityQueue; | |
public class DiceGame { | |
/* | |
* We are playing a dice game. | |
* Player A plays with 2 dice. | |
* Player B plays with 3 dice. | |
* Player A adds up the eyes of both rolls. | |
* Player B chooses the two highest and adds up these. | |
* If both eyes are equal player A wins. | |
* What are the probabilities for both players to win? | |
*/ | |
public static void main(String[] args) { | |
int an = 0; | |
int bn = 0; | |
int n = 1000000; | |
for (int i = 0; i < n; i++) { | |
int a = nkrand(2, 2); | |
int b = nkrand(2, 3); | |
if (a >= b) an++; // if equals a wins | |
if (a < b) bn++; | |
} | |
System.out.println("A: " + (double) an / n); | |
System.out.println("B: " + (double) bn / n); | |
} | |
/** | |
* A function that returns the eyes total of the highest n rolls of overall k rolls | |
* @param n add up the highest n numbers | |
* @param k from k rolls | |
*/ | |
private static int nkrand(int n, int k) { | |
if (n > k) throw new Error(); | |
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x); | |
for (int i = 0; i < k; i++) { | |
pq.add(rand()); | |
} | |
int sum = 0; | |
for (int i = 0; i < n; i++) { | |
sum += pq.poll(); | |
} | |
return sum; | |
} | |
private static int rand() { | |
return ((int) (Math.random()*6)) + 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment