/************************************************************ ; * ; William M. Spears * ; Navy Center for Applied Research in AI * ; Naval Research Laboratory * ; * ; This software is the property of the Department of the * ; Navy. Permission is hereby granted to copy all or any * ; part of this program for free distribution, however * ; this header is required on all copies. * ; * ; File: utility.c * ;************************************************************/ #include "header.h" /* Keep track of the generation number...*/ void time_keeper () { gen_time++; printf("\nIteration %d, Generation %d, Evaluations %d: \n", iteration, gen_time, evals); } /* Return a random integer from low to high */ short rrandom (low, high) short low, high; { long random(); short nb = high - low + 1; return(random() % nb + low); } /* Return a random integer from 1 to n inclusive.*/ int myrand (n) int n; { short rrandom(); return(rrandom(1, n)); } /* Return a random real from (0.0 1.0).*/ double ssrand () { short rrandom(); return((double)(1 + rrandom(1, 31998)) / 32000.0); } /* Return a random bit (0 or 1).*/ int brand () { short rrandom(); return(rrandom(0, 1)); } /********************************************************/ /* Display individual i. */ void show_individual (i) { int j; for (j = 1; j <= length; j++) printf("%d", c[i][j]); printf("\n"); } /* Display whole population. */ void show_pop () { int i; for (i = 1; i <= size; i++) { printf("Individual %d: ", i); show_individual(i); } } /* Display best individual seen so far. */ void show_best_individual () { int i; for (i = 1; i <= length; i++) printf("%d", b[i]); } /* Print best individual in a file. */ void fshow_best_individual (fp) FILE *fp; { int i; for (i = 1; i <= length; i++) fprintf(fp, "%d", b[i]); } /********************************************************/ /* Swap takes as input pointers to 2 elements and swaps them. */ swap_elements(x,y) /* Interchange two elements */ int *x,*y; { int temp; temp = *x; *x = *y; *y = temp; } /* Selectsort takes as input an array and its size and performs a selection sort on this array. */ selectsort(n, a) /* Perform a selectsort */ int n, a[]; { register int small, j, k; for(k = 0; k < n - 1;k++) { small = k; for(j = k + 1; j < n; j++) { /* Select the smallest */ if (a[j] < a[small]) /* from among a[k],...,a[n-1]*/ small = j; /* and swap with a[k]. */ } swap_elements(&a[k],&a[small]); } }