// Population.cpp: implementation of the Population class. // ////////////////////////////////////////////////////////////////////// #include "Population.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Population::Population(int size, int rules) : g(size) { this->rules = rules; } Population::~Population() { h.clear(); } void Population::print(FILE* f, long step) { fprintf(f, "%4ld ", step); g.print(f); fprintf(f, "\n"); } void Population::randomize() { int i; for(i = 0; i < g.getSize(); i++) g[i] = (rand() < (RAND_MAX / 2)) ? 1 : 0; } void Population::normalize() { Generation temp = g; int i; for(i = 0; i < g.getSize() - 1; i++) { temp.rotateLeft(); if(temp < g) g = temp; } } int Population::run(long limit, long& total, long& period, int flags) { int i, j; long position; Generation temp = g; if(flags & 128) normalize(); if(flags & 4) print(stderr, total); if(flags & 32) print(stdout, total); while(limit--) { ++total; for(i = 0, j = g.getSize() - 1; i < g.getSize(); i++, j++) { if(j >= g.getSize()) j = 0; temp[i] = getResultForPatternAt(j); } g = temp; if(flags & 128) normalize(); if(flags & 4) print(stderr, total); if(flags & 32) print(stdout, total); if((position = h.find(&g)) > 0) { period = total - position; total = position; return 1; } h.append(new Generation(g), total); } period = 0; return 0; } CELL Population::getResultForPatternAt(int index) { int i, patternID = 0; for(i = 2; i >= 0; i--, index++) { if(index >= g.getSize()) index %= g.getSize(); patternID |= (g[index] << i); } return ((rules & (1 << patternID)) > 0) ? 1 : 0; }