/*
 * simdonk.c - simulate Car and Donkeys problem.
 * Pekka Taipale <pjt@iki.fi> Jan 28 1996
 *
 * See <URL:http://www.iki.fi/pjt/problem/4.html> for a description of
 * the problem.
 */

#include <stdlib.h>
#include <time.h>

/* 
 * host_notopen()
 * This function is given the boxes and the selection of the competitor.
 * It returns a number of the remaining box that the host does NOT open, 
 * i.e. either the box that has car or an empty box, if the competitor's
 * original selection contains a car.
 */

int host_notopen(int box[3], int selection)
{
  if (box[(selection + 1) % 3])
    return ((selection + 1) % 3);
  else
    return ((selection + 2) % 3);
}

/*
 * The main program gets number of simulation rounds in argv[1]
 */


int main(int argc, char *argv[])
{
  int box[3];
  int selection;
  int n = 0;
  int keep_wins = 0;
  int change_wins = 0;
  int rounds = 10000; /* run 10000 rounds if not given on command line */

  if (argc == 2)
    rounds = atoi(argv[1]);

  srandom((unsigned int) time(NULL));

  for (n = 0; n < rounds; n++) {
    box[0] = box[1] = box[2] = 0;       /* donkeys */
    box[((int) random()) % 3] = 1;      /* car */
    selection  = ((int) random()) % 3;  /* competitor selects */
    if (box[selection])
      keep_wins++;
    if (box[host_notopen(box, selection)])
      change_wins++;
  }
      
  printf("Keep wins %d times (%d%%)\n", 
	 keep_wins, (100 * keep_wins / rounds));
  printf("Change wins %d times (%d%%)\n", 
	 change_wins, (100 * change_wins / rounds));
}