/* opt_findx v0.1 - Core War find-x number calculator by John Metcalf * using the bomb-free space method * Usage: opt_findx coresize find [modulo] */ #include #include #define MAXCORESIZE 65535 #define TOPX 50 int gcd( int a, int b ) { return !b ? a : gcd( b, a % b ); } int qcmp (const void *pa, const void *pb ) { const unsigned *a = pa; const unsigned *b = pb; if ( a[1] < b[1] ) return -1; if ( a[1] > b[1] ) return 1; return 0; } int findx(int step, int coresize, int find) { int high, low, pos, score = 0; high = low = pos = step; while (pos != 0 && coresize - high + low > find) { pos = (pos + step) % coresize; if (pos > high) high = pos; if (pos < low) low = pos; score++; } return score; } int main(int argc, char *argv[]) { unsigned scores[MAXCORESIZE][2] = {0}; unsigned step, coresize, i, index=0, modulo=1, find; if (argc < 3) { printf("\nFINDX - Core War find-x number calculator\n" "\nUsage: %s coresize find [modulo]\n",argv[0]); return 0; } coresize = atoi(argv[1]); find = atoi(argv[2]); if (argc > 3) { modulo = atoi(argv[3]); } if (coresize%modulo != 0) { printf("\nERROR: modulo is not a factor of coresize\n"); return 1; } if (coresize > MAXCORESIZE) { printf("\nERROR: coresize out of range\n"); return 1; } for (step = modulo; step < (coresize + 1) / 2; step += modulo) { if (gcd(coresize, step) == modulo) { scores[index][0] = step; scores[index][1] = findx(step, coresize, find); index++; } } qsort(scores, index, sizeof scores[0], qcmp); printf("\n Step Score\n\n"); for (i = 0; i < index && i < TOPX; i++) { printf("%7u %7u\n", scores[i][0], scores[i][1]); } }