Skip to content

Instantly share code, notes, and snippets.

@joriki
Created December 16, 2012 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joriki/4313328 to your computer and use it in GitHub Desktop.
Save joriki/4313328 to your computer and use it in GitHub Desktop.
Find cycles of three six-sided dice such that each beats the next one with the same maximal probability; see http://math.stackexchange.com/questions/260072.
public class Question260072 {
public static void main (String [] args) {
int [] [] dice = new int [3] [6];
int [] counter = new int [3];
int limit = (int) Math.pow (3,18);
int max = 0;
outer:
for (int selection = 0;selection < limit;selection++) {
// transform 18-digit ternary number into die sides
counter [0] = counter [1] = counter [2] = 0;
int n = selection;
for (int i = 0;i < 18;i++) {
int die = n % 3;
if (counter [die] == 6)
continue outer;
dice [die] [counter [die]++] = i;
n /= 3;
}
// determine winning probabilities
counter [0] = counter [1] = counter [2] = 0;
for (int i = 0;i < 3;i++)
for (int j = 0;j < 6;j++)
for (int k = 0;k < 6;k++)
if (dice [i] [j] > dice [(i + 1) % 3] [k])
counter [i]++;
// are they all the same and maximal?
if (counter [0] >= max && counter [0] == counter [1] && counter [1] == counter [2]) {
max = counter [0];
if (max == 21) {
// if this is an optimal set, print it only if the 0 is in the first set to avoid cyclic equivalents
boolean zeroHasZero = false;
for (int i = 0;i < 6;i++)
zeroHasZero |= dice [0] [i] == 0;
if (zeroHasZero) {
// collapse successive numbers on the same die into one
int lastDie = -1;
int lim = 18;
for (int i = 0;i < lim;) {
int die;
inner:
for (die = 0;die < 3;die++)
for (int k = 0;k < 6;k++)
if (dice [die] [k] == i)
break inner;
if (die == 4)
throw new Error ();
if (die == lastDie) {
for (int j = 0;j < 3;j++)
for (int k = 0;k < 6;k++)
if (dice [j] [k] >= i)
dice [j] [k]--;
lim--;
}
else {
lastDie = die;
i++;
}
}
// print the collapsed optimal set
for (int i = 0;i < 3;i++) {
System.out.print (" ");
for (int j = 0;j < 6;j++)
System.out.printf (" %d",dice [i] [j]);
System.out.println ();
}
System.out.println ();
}
}
}
}
System.out.println (max);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment