int main(int argc, char *argv[]) { int numberCells; int generations; int *cells; int *nextGen; int i, x = 0; if(argc != 3) { fprintf(stderr, "usage: %s numCells numGens\n", argv[0]); exit(1); } numberCells = atoi(argv[1]); generations = atoi(argv[2]); srand((unsigned) time(0)); cells = (int *) calloc(numberCells, sizeof(int)); nextGen = (int *) calloc(numberCells, sizeof(int)); if(cells == NULL || nextGen == NULL) { fprintf(stderr, "Error! Memory allocation failed!\n"); exit(1); } for(i = 1; i < numberCells - 1; i++) { *(cells + i) = rand() % 2; } printGeneration(numberCells, cells); while(x < generations) { computeNextGenP(numberCells, cells, nextGen); printGeneration(numberCells, nextGen); x++; } free(cells); free(nextGen); print_memory_leaks(); return 0; }
/** * Selects the new generation by mating two individuals selected * probabilistically by their fitness. * Point 3 of page 7 in paper by Mitchell. */ void make_new_generation() { int i,j,k; int totalFitness = calculateFitnesses(); rule_t* next_population = populations[1-p_buf]; if (generation % GENERATION_PRINT_SEQUENCE == 0) { printGeneration(); } // Create new generation for (i=0; i<POPULATION_SIZE; i++) { int index1 = 0, index2 = 0; int map1 = (int) random_max(totalFitness); int map2 = (int) random_max(totalFitness); bool done1 = false; bool done2 = false; // Find individuals to mate for (j=0, k=0; j < POPULATION_SIZE; j++) { if (done1 && done2) break; k += population[j].fitness; if (!done1 && k >= map1) { index1 = j; done1 = true; } if (!done2 && k >= map2) { index2 = j; done2 = true; } } rule_mate(population+index1, population+index2, next_population+i, next_population+i+1); i++; } p_buf = 1-p_buf; population = next_population; }
//--------------------------------------------------------------------- // Function: main(void) // Title: Main // Description: Main function for the game of life // Programmer: TSZ HIN FUNG // Date: 12/1/2014 // Version: 1.00 // Environment: Intel Xeon PC // Software: MS Windows 7 for execution; // Compiles under Microsoft Visual Studio.Net 2010 // Parameter: void // Input: NONE // Output: Generation with frame // Calls: printGeneration // swapPointer // calcNextGeneration // readlife // Return: EXIT_SUCCESS // History Log: // 12/1/2014 THF completed version 1.0 // -------------------------------------------------------------------- int main(void) { int generation[ROW][COLUMN] = {0}; int nextGeneration[ROW][COLUMN] = {0}; int (*pointerOne)[COLUMN] = generation; int (*pointerTwo)[COLUMN] = nextGeneration; int numberOfGeneration = 0; char token = ' '; readlife(pointerOne); do { system("cls"); printf("Generation: %d\n", numberOfGeneration); numberOfGeneration++; printGeneration(pointerOne); calcNextGeneration(pointerOne, pointerTwo); swapPointer(&pointerOne, &pointerTwo); printf("Press Enter to continue, other keys to quit..."); token = getch(); } while(token == '\r' || token == '\n' ); return EXIT_SUCCESS; }