#include <math.h>

#define MAX_ATTACKERS 50
#define ATTACK_HIT 1
#define DEFEND_HIT 2
#define TEST_COUNT 100000

int runcombat(long att0, long def0, long count);

int main() {
  long def0, att0;

  for (att0 = 1; att0 < MAX_ATTACKERS + 1; att0++) {
    /* first try with 1 fewer */
    def0 = (int) ((double) att0) / M_SQRT2;  /* defenders rounded down */

    printf("%2d to %2d: ", att0, def0);

    if (runcombat(att0, def0, TEST_COUNT) > TEST_COUNT / 2)
      printf("attacker wins (CONFIRMED), ");
    else
      printf("defender wins (*FAILED*),  ");

    /* now try with one more */
    def0 = def0 + 1;
    
    printf("%2d to %2d: ", att0, def0);

    if (runcombat(att0, def0, TEST_COUNT) < TEST_COUNT / 2)
      printf("defender wins (CONFIRMED)\n");
    else
      printf("attacker wins (*FAILED*)\n");
  }
}

int runcombat(long att0, long def0, long count) {
  long def, att; /* current count for sides */
  long awins = 0; /* total number of wins for each side */
  long dhits, ahits; /* number of hits per round */
  long i, j;

  for (i = 0; i < count; i++) {
    /* Run a trial combat */
    def = def0;
    att = att0;
    while (att > 0 && def > 0) {
      /* Go through each round until one side wins */
      dhits = ahits = 0;
      for (j = 0; j < def; j++) /* defender attacks */
	if (lrand48() % 6 < DEFEND_HIT)
	  dhits++;
      for (j = 0; j < att; j++) /* attacker attacks */
	if (lrand48() % 6 < ATTACK_HIT)
	  ahits++;
      def -= ahits;
      att -= dhits;
    }
    /* Determine who won */
    if (att > 0)
      awins++;
  }

  return awins;
}

