/* main-A171884.c 20100311 Copy from A097486 20100312 Add -l, -s and -h options */ #include // defines size_t #include // defines malloc #include #define DEFAULT_SIZE_LIM 100 long * g_l; long g_alloc; long g_lowestval; long g_startval; /* Search for an item, return a negative result if it is not found */ long cw2010_seek(long * haystack, long size, long needle); long cw2010_seek(long * haystack, long size, long needle) { long i; for(i=0; i best) { best = l[i]; } } return(best); } /* Return true if there is a direct "escape route" by going up each time. Non-recursive and a little faster than a general escape search. */ long cw2010_escdir_p(long * l, long size); long cw2010_escdir_p(long * l, long size) { long largest; long i, n; if (size==0) { return(1); } largest = cw2010_largest(l, size); if (l[size-1] == largest) { return(1); } i = size; n = l[i-1]; while(n < largest) { n = n + i; i = i+1; if (cw2010_seek(l, size, n)) { return(0); } } return(1); } /* Return true if the "down" next term option is legal */ long cw2010_down_p(long * l, long size); long cw2010_down_p(long * l, long size) { long t; t = l[size-1] - size; if ((t < g_lowestval) || (cw2010_seek(l, size, t) >= 0)) { return(0); } return(1); } /* Return true if the "up" next term option is legal */ long cw2010_up_p(long * l, long size); long cw2010_up_p(long * l, long size) { long t; t = l[size-1] + size; if (cw2010_seek(l, size, t) >= 0) { return(0); } return(1); } /* Recursive algorithm, seeks an escape route preferring the "upper path" at each choice in order to find an exit quickly. */ long cw2010_escape_p(long * l, long size); long cw2010_escape_p(long * l, long size) { long i; /* First try the direct route, which will save time on the recursive backtracking */ if (cw2010_escdir_p(l, size)) { return(1); } if (size >= g_alloc) { fprintf(stderr, "cw2010_esc_p: Reached allocation limit."); exit(-1); } if (cw2010_up_p(l, size)) { l[size] = l[size-1] + size; // if(cw2010_escape_p(l, size+1)) { // return(1); // } return(cw2010_escape_p(l, size+1)); } if (cw2010_down_p(l, size)) { l[size] = l[size-1] - size; return(cw2010_escape_p(l, size+1)); } return(0); } /* Report the holes in a list */ void cw2010_holes(long * l, long size); void cw2010_holes(long * l, long size) { long largest, i, first, prev; first = 1; prev = -1; printf("Holes: "); largest = cw2010_largest(l, size); for(i=g_lowestval; i= '0') && (c <= '9')) { sscanf(argv[i], "%ld", &g_alloc); } } } if (g_alloc < 10) { fprintf(stderr, "A171884: max must be at least 10; I got %ld\n", g_alloc); exit(-1); } printf("Parameters: start %ld lowest %ld numterms %ld\n", g_startval, g_lowestval, g_alloc); /* Convert desired number of terms to array allocation size */ g_alloc = 2 * (g_alloc - 1); g_l = (long *) malloc(sizeof(long) * g_alloc); cw2010_a(); return(0); } /* end of main-A171884.c */