static double averageUtility(double x) {
int sum = 0;
for(int i = 0; i < trials; i++) {
sum += utility(x); //iteratively generates the sum to be divided
}
return (sum / trials); //averages the utility function over some number of trials
}
static void setupUtilities(int slices) { //slices is just the number of different values of p we’ll be testing, or how finely we slice up the unit interval
utilities = new double[slices];
for(int i = 0; i < slices; i++) {
utilities[i] = averageUtility((double) i / slices);
}
}
import java.util.*;
public class absentMindedDriver {
static Random generator = new Random(); static int trials = 100000; static double[] utilities;
static int utility(double x) { if(generator.nextDouble() < x) { //the driver guesses return 0; } if(generator.nextDouble() < x) { //the driver guesses return 4; } return 1; //the driver missed both exits }
static double averageUtility(double x) { int sum = 0; for(int i = 0; i < trials; i++) { sum += utility(x); //iteratively generates the sum to be divided } return (sum / trials); //averages the utility function over some number of trials }
static void setupUtilities(int slices) { //slices is just the number of different values of p we’ll be testing, or how finely we slice up the unit interval utilities = new double[slices]; for(int i = 0; i < slices; i++) { utilities[i] = averageUtility((double) i / slices); } }
static double maxP(int slices) { double bestPSoFar = 0; double bestUtilSoFar = 0; setupUtilities(slices); for(int i = 0; i < slices; i++) { if(utilities[i] > bestUtilSoFar) { bestPSoFar = ((double) i / slices); } } return bestPSoFar; }
public static void main(String[] args) { System.out.println(maxP(100)); } }