Baseball Riddle
R Input:
mean(sapply(1:1e5, function(x)
max(sapply(1:5, function(y) sum(rbinom(162, 1, 0.5))))))
Output:
[1] 88.37343
For more simulations, do it in C.
Input:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Get the maximum of an integer array x of size n */
int getMax(int x[], int n)
{
int max = 0; // number of wins is nonnegative.
int i;
for (i = 0; i < n; ++i) {
if (x[i] > max) {
max = x[i];
}
}
return max;
}
/* Find the average number of wins by the winner in nreps simulations */
double avgWinsByWinner(int nreps)
{
int num_teams = 5;
int num_games = 162;
int num_wins[num_teams];
float draw;
double avg_winner_wins;
srand(time(NULL));
int i, j, k;
for (i = 0; i < nreps; ++i) {
for (j = 0; j < num_teams; ++j) {
num_wins[j] = 0;
for (k = 0; k < num_games; ++k) {
draw = (float) rand() / (float) RAND_MAX;
if (draw > 0.5) {
num_wins[j] += 1;
}
}
}
avg_winner_wins += (double) getMax(num_wins, num_teams) / nreps;
}
return avg_winner_wins;
}
void main()
{
int nreps = 10000000;
printf("Average number of wins by the winner: %f\n", avgWinsByWinner(nreps));
}
Output:
Average number of wins by the winner: 88.398873