Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Calculate the value of a game that involves rerolling dice; see http://math.stackexchange.com/questions/1118263.
import java.math.BigInteger;
import java.util.Arrays;
public class Question1118263 {
final static int [] values = {1,2,3,4,5,6};
final static int nsides = values.length;
final static int ndice = 20;
public static void main (String [] args) {
Rational [] v = new Rational [ndice];
Arrays.fill (v,Rational.ZERO);
Rational p = Rational.ONE;
for (int n = 1;n < ndice;n++) {
long start = System.currentTimeMillis ();
p = p.divide (BigInteger.valueOf (nsides));
int [] dice = new int [n];
int lim = (int) Math.pow (nsides,n);
for (int i = 0;i < lim;i++) {
int sum = 0;
for (int j = 0,k = i;j < n;j++,k /= nsides)
sum += dice [j] = values [k % nsides];
Arrays.sort (dice);
Rational max = Rational.ZERO;
for (int reroll = 0;reroll < n;reroll++) {
Rational newValue = v [reroll].add (sum);
if (newValue.compareTo (max) > 0)
max = newValue;
sum -= dice [reroll];
}
v [n] = v [n].add (max);
}
v [n] = v [n].multiply (p);
System.out.println (n + " : " + v [n]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment