示例#1
0
void Genetic::workout(std::ostream & fout) {
  // Answer answer(ncity);

  Answer ** colony = new Answer*[SIZE];
  for (size_t i = 0; i < SIZE; i++) {
    colony[i] = new Answer(ncity);
  }
  Answer ** nextGene = new Answer*[SIZE];
  for (size_t i = 0; i < SIZE; i++) {
    nextGene[i] = new Answer(ncity);
  }

  int t = 0;
  double bestAnswer = 0.0;
  int bestGeneId = -1;

  initPopulation(colony, SIZE);

  int gene_num = 1000 * ncity;
  while (t < gene_num) { // 结束条件: 遗传代数到达城市数目的1000倍

    bestGeneId = nextGeneration(colony, nextGene);
    bestAnswer = total_cost(*colony[bestGeneId]);
    // print(fout, colony[bestGeneId]);

    // (9)
    for (size_t i = 0; i < SIZE; i++) {
      *colony[i] = *nextGene[i];
    }
    t = t + 1;
  }
  // (10)
  print(fout, colony[bestGeneId]);
  std::cout << bestAnswer << std::endl;
}
void FixedQueueIndexManager::abortPushIndexReservation(unsigned int generation,
                                                       unsigned int index)
{
    BSLS_ASSERT(generation <= d_maxGeneration);
    BSLS_ASSERT(index      <  d_capacity);
    BSLS_ASSERT(static_cast<unsigned int>(d_popIndex.loadRelaxed()) ==
                generation * d_capacity + index);
    BSLS_ASSERT(e_WRITING  == decodeStateFromElementState(d_states[index]));
    BSLS_ASSERT(generation ==
                decodeGenerationFromElementState(d_states[index]));

    unsigned int loadedPopIndex = d_popIndex.loadRelaxed();

    // Note that the preconditions for this function -- that the current thread
    // (1) holds a push-index reservation on 'generation' and 'index', and (2)
    // has called 'clearPopIndex' on all the preceding generation and index
    // values -- require that 'd_popIndex' refer to 'generation' and 'index.

    BSLS_ASSERT(generation == loadedPopIndex / d_capacity);
    BSLS_ASSERT(index      == loadedPopIndex % d_capacity);

    // Marking the cell first for reading in the current generation, and then
    // after incrementing the pop index, marking it empty for the subsequent
    // generation matches the states when popping the cell.  Although the
    // intermediate 'e_READING' state is not strictly necessary, it reduces the
    // set of states that 'reservePopIndex' may encounter.

    d_states[index] = encodeElementState(generation, e_READING);

    unsigned int nextIndex = nextCombinedIndex(loadedPopIndex);
    d_popIndex.testAndSwap(loadedPopIndex, nextIndex);

    d_states[index] = encodeElementState(nextGeneration(generation), e_EMPTY);

}
void GeneticAlgorithm::evolve() {

	std::fstream file("log.txt", std::ios::out);

	file << "generation\t average fit\t best fit\t worst fit "<< std::endl;

	initPopulation();

	for(_generation = 0; _generation < _maxGenerations; ++_generation) {
		nextGeneration();

		file << _generation << "\t" << _averageFit << "\t" << _bestFit << "\t" << _worstFit << std::endl;
	}

	file.close();
}
void FixedQueueIndexManager::commitPopIndex(unsigned int generation,
                                            unsigned int index)
{
    BSLS_ASSERT(generation <= d_maxGeneration);
    BSLS_ASSERT(index      <  d_capacity);
    BSLS_ASSERT(e_READING  == decodeStateFromElementState(d_states[index]));
    BSLS_ASSERT(generation ==
                decodeGenerationFromElementState(d_states[index]));

    // We cannot guarantee the full preconditions of this function.  The
    // preceding assertions are as close as we can get.

    // Mark the popped cell with the subsequent generation and the EMPTY state.

    d_states[index] = encodeElementState(nextGeneration(generation),
                                         e_EMPTY);
}
示例#5
0
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void elMundo::make4guns(const char *param_string)
{
    QString params(param_string);
    params.append(".........");
    char c, sign[10] =                          "....:....";
    int N = 0, i;
    for (i = 0; i < 4; i++) {
        if (('A' <= (c = params[i].unicode()) && c <= 'Z') ||
                ('a' <=  c                        && c <= 'z')) sign[i] = c;
        else {
            N = rand() % 52;
            sign[i] = (N < 26) ? (N+'A') : (N-26+'a');
        }
    }
    for (i = 0; i < 4; i++) {
        if (('0' <= (c = params[i+5].unicode()) && c <= '7')) sign[i+5] = c;
        else {
            N = rand() % 8;
            sign[i+5] = N+'0';
        }
    }
#define PASTE_1GUN(A,Z,k,x,y,M,color) \
  if (A <= (c = sign[k]) && c <= Z) { \
    i = sign[k+5] - '0';              \
    pasteGun1(gunCfg[i].x, gunCfg[i].y, c, gunCfg[i].rle, M, color); \
  }
    PASTE_1GUN('A','Z',0,x1,y1,Id,elcRed);
    PASTE_1GUN('A','Z',1,x2,y2,Ro,elcYellow);
    PASTE_1GUN('A','Z',2,x3,y3,Rx,elcGreen);
    PASTE_1GUN('A','Z',3,x4,y4,Rc,elcBlue);
    nextGeneration();
    PASTE_1GUN('a','z',0,x1,y1,Id,elcRed);
    PASTE_1GUN('a','z',1,x2,y2,Ro,elcYellow);
    PASTE_1GUN('a','z',2,x3,y3,Rx,elcGreen);
    PASTE_1GUN('a','z',3,x4,y4,Rc,elcBlue);
    add(0,0,0);
    fprintf(stderr, "4guns(%s,%d:%d:%d:%d)\n", sign, gunCfg[sign[5]-'0'].p,
            gunCfg[sign[6]-'0'].p,
            gunCfg[sign[7]-'0'].p,
            gunCfg[sign[8]-'0'].p);
}
示例#6
0
void GaTTP::Solve() {

    // Gera uma populacao randomica inicial
    GenerateInitial();
    current->CalcFitness();

    do{

        // Realiza a selecao dos pais
        current->SelectParents(eliteRate);

        // Realiza a reproducao por mutacao, crossover e elitismo
        current->ParentsMutation(pRate, mRate);
        current->ParentsCrossover(cRate);

        nextGeneration();

    }while(!verifyStoppage()); // verifica condicao de parada

    std::cout << "Tempo Total: ";
    std::cout << StrTimeElapsed() << std::endl;
    std::cout << "Total de geracoes: ";
    std::cout << generation << std::endl;
    std::cout << "**** Solucao **** ";
    std::cout << current->GetBestIndividual()->ToString(teams);

    std::ofstream out(outputFile.c_str(), std::ofstream::out);
    out << "Tempo Total: ";
    out << StrTimeElapsed() << std::endl;
    out << "Total de geracoes: ";
    out << generation << std::endl;
    out << "**** Solucao **** ";
    out << current->GetBestIndividual()->ToString(teams);
    out.close();

    delete current;


}
示例#7
0
int main(short int argc, char** argv) {

	al_init();
	al_install_keyboard();
	al_install_mouse();
	al_init_image_addon();
	al_init_font_addon();
	al_init_ttf_addon();

	ALLEGRO_MONITOR_INFO oMonitorInfo;
	al_get_monitor_info(0, &oMonitorInfo);

	short int iDisplayWidth = oMonitorInfo.x2 * 0.70f;
	short int iDisplayHeight = oMonitorInfo.y2 * 0.70f;
	short int iAppWidth = iDisplayWidth * 0.95f;
	short int iAppHeight = iDisplayHeight * 0.95f;
	short int iMarginHorizontal = (iDisplayWidth - iAppWidth) / 2;
	short int iMarginVertical = ((iDisplayHeight - iAppHeight) / 2);
	int iGenerations = 0;
	short int iFPS = 30;
	float iLifeMin = 3.0f;
	float iLifeMax = 37.0f;	
	short int iFontSize = (iDisplayWidth > 1024) ? 12 : 10;
	if (iDisplayWidth < 800) {
		iFontSize = 8;
	}
	long int iSimulations = 1;

	std::random_device rd;
	std::mt19937 mt(rd());
	std::uniform_real_distribution<double> dist(iLifeMin, iLifeMax);
	
	int iLifeScarcity = std::round(dist(mt));

	bool** pCells = new bool*[iAppWidth];
	bool** pNextGenCells = new bool*[iAppWidth];

	initCells(pCells, pNextGenCells, iAppWidth, iAppHeight, iLifeScarcity);

	ALLEGRO_DISPLAY* pDisplay = al_create_display(iDisplayWidth, iDisplayHeight);	
	ALLEGRO_EVENT_QUEUE* pQueue = al_create_event_queue();	
	ALLEGRO_TIMER* pTimer = al_create_timer(1.0f / iFPS);
	ALLEGRO_TIMER* pSecondBySecondTimer = al_create_timer(1.0f);
	ALLEGRO_BITMAP* pBuffer = al_create_bitmap(iAppWidth, iAppHeight);
	ALLEGRO_COLOR oBackgroundColor = al_map_rgb(0, 0, 0);
	ALLEGRO_COLOR oCellColor = al_map_rgb(randr(150, 255), randr(150, 255), randr(150, 255));
	ALLEGRO_FONT* oFont = al_load_ttf_font("VeraMono.ttf", iFontSize, 0);
	ALLEGRO_FONT* oFontLarge = al_load_ttf_font("VeraMono.ttf", (iFontSize * 3), 0);

	al_inhibit_screensaver(true);
	
	al_register_event_source(pQueue, al_get_keyboard_event_source());
	al_register_event_source(pQueue, al_get_mouse_event_source());	
	al_register_event_source(pQueue, al_get_timer_event_source(pTimer));
	al_register_event_source(pQueue, al_get_timer_event_source(pSecondBySecondTimer));
	al_set_target_backbuffer(pDisplay);
	al_clear_to_color(oBackgroundColor);
	al_flip_display();

	al_start_timer(pTimer);
	al_start_timer(pSecondBySecondTimer);

	ALLEGRO_EVENT oEvent;

	short int iBufferUsed = 0;
	short int iBufferDrawn = 0;
	bool bRedraw = false;
	std::string sHeaderStatistics = "GEN  [GENXXXXX]     FPS  [FPSXXXXX]     CELLS  [CELLSXXXXX]    GENS/S  [GENSSXXXXX]    SCARCTY  [SCARXXXXX]    TIME  [TIMEXXXXX]";
	std::string sHeaderStats = "";
	/* std::string sHeaderText_2 = "";
	std::string sHeaderText_3 = "";
	std::string sHeaderText_4 = "";
	std::string sHeaderText_5 = "";
	std::string sHeaderText_6 = ""; */
	std::string sCountdownText = "";
	std::string sSimulations = "";
	std::string sStats = "CELLS: ";

	sStats.append(std::to_string((iAppWidth * iAppHeight)));
	sStats.append(", MAP SIZE (KB): ");
	sStats.append(std::to_string((iAppWidth * iAppHeight * sizeof(bool)) / 1024));
	sStats.append("  (SPACE) Pause (C)olor, (R)eload, (S)carcity, (F) +1 FPS, (G) -1 FPS, (ESC) Exit");

	long int iTotalAlive = 0;
	int iPatternStableBuffer = (iFPS * 4);
	long int* iTotalPatternStable = new long int[iPatternStableBuffer];
	short int iTotalPatternCounter = 0;
	long int iSecondsRunning = 0;

	float fPosText2 = (iAppWidth * 0.15);
	float fPosText3 = (iAppWidth * 0.30);
	float fPosText4 = (iAppWidth * 0.50);	
	float fPosText5 = (iAppWidth * 0.70);
	float fPosText6 = (iAppWidth * 0.85);

	float fPosTextSim = (iAppWidth * 0.75);

	bool bPatternIsStable = false;
	int iCountdownSeconds = 10;

	bool bDrawingOn = false;
	bool bTimerStopped = false;

	ALLEGRO_COLOR oRandColor = al_map_rgb(randr(0, 255), randr(0, 255), randr(0, 255));

	while (true) {
		
		al_wait_for_event(pQueue, &oEvent);

		if (oEvent.type == ALLEGRO_EVENT_TIMER) {
			if (!bTimerStopped) {
				if (oEvent.timer.source == pTimer) {

					iTotalAlive = 0;
					redrawCells(pBuffer, pCells, pNextGenCells, iAppWidth, iAppHeight, oCellColor, oBackgroundColor);
					nextGeneration(pCells, pNextGenCells, iAppWidth, iAppHeight, iTotalAlive);
					al_set_target_backbuffer(pDisplay);
					al_clear_to_color(oBackgroundColor);
					al_draw_bitmap(pBuffer, iMarginHorizontal, iMarginVertical, 0);

					sHeaderStats = ReplaceString(sHeaderStatistics, "[GENXXXXX]", std::to_string(iGenerations));
					sHeaderStats = ReplaceString(sHeaderStats, "[FPSXXXXX]", std::to_string(iFPS));
					sHeaderStats = ReplaceString(sHeaderStats, "[CELLSXXXXX]", std::to_string(iTotalAlive));
					sHeaderStats = ReplaceString(sHeaderStats, "[SCARXXXXX]", std::to_string(iLifeScarcity));
					sHeaderStats = ReplaceString(sHeaderStats, "[TIMEXXXXX]", std::to_string(iSecondsRunning));
					if (iGenerations > 0 && iSecondsRunning > 0) {
						sHeaderStats = ReplaceString(sHeaderStats, "[GENSSXXXXX]", std::to_string(iGenerations / iSecondsRunning));
					}
					else {
						sHeaderStats = ReplaceString(sHeaderStats, "[GENSSXXXXX]", "0");
					}					
					sSimulations = "SIMS ";
					sSimulations.append(std::to_string(iSimulations));
					int iLengthSims = al_get_text_width(oFont, sSimulations.c_str());
					int iLengthStats = al_get_text_width(oFont, sHeaderStats.c_str());
					al_draw_text(oFont, oCellColor, ((iAppWidth - iLengthStats) / 2), 1.0f, 0, sHeaderStats.c_str());
					al_draw_text(oFont, oCellColor, (iDisplayWidth - (iLengthSims + 25.0f)), (iAppHeight + iMarginVertical + 5.0f), 0, sSimulations.c_str());
					al_draw_text(oFont, oCellColor, 25.0f, (iAppHeight + iMarginVertical + 5.0f), 0, sStats.c_str());

					if (bPatternIsStable == true) {
						sCountdownText.clear();
						sCountdownText.append("PATTERN STABILIZED, RESTARTING IN... ");
						int iLengthStr = al_get_text_width(oFontLarge, sCountdownText.c_str());
						sCountdownText.append(std::to_string(iCountdownSeconds));
						al_draw_text(oFontLarge, oRandColor, ((iAppWidth - iLengthStr) / 2), (iAppHeight * 0.45f), 0, sCountdownText.c_str());
					}

					al_flip_display();
					++iGenerations;
					copyCells(pCells, pNextGenCells, iAppWidth, iAppHeight);

					if (iTotalPatternCounter == iPatternStableBuffer) {
						bPatternIsStable = isPatternStable(iTotalPatternStable, iPatternStableBuffer);
						delete iTotalPatternStable;
						iTotalPatternStable = new long int[iPatternStableBuffer];
						iTotalPatternCounter = 0;
					}
					iTotalPatternStable[iTotalPatternCounter] = iTotalAlive;
					++iTotalPatternCounter;
				}

				if (oEvent.timer.source == pSecondBySecondTimer) {
					if (bPatternIsStable == true) {
						if (iCountdownSeconds > 1) {
							--iCountdownSeconds;
						}
						else {
							bPatternIsStable = false;
							iTotalPatternCounter = 0;
							iGenerations = 0;
							iSecondsRunning = 0;
							iCountdownSeconds = 10;
							++iSimulations;
							clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
							randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);
						}
					}
					else {
						iCountdownSeconds = 10;
					}
					++iSecondsRunning;
					oRandColor = al_map_rgb(randr(0, 255), randr(0, 255), randr(0, 255));
				}
			}
		}

		if (oEvent.type == ALLEGRO_EVENT_KEY_DOWN) {
			
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {				
				break;
			}

			if (oEvent.keyboard.keycode == ALLEGRO_KEY_SPACE) {
				if (!bTimerStopped) {					
					bTimerStopped = true;
					al_stop_timer(pTimer);
				}
				else {					
					bTimerStopped = false;
					al_start_timer(pTimer);
				}				
			}

			if (oEvent.keyboard.keycode == ALLEGRO_KEY_R) {
				bPatternIsStable = false;
				iTotalPatternCounter = 0;
				iGenerations = 0;
				iSecondsRunning = 0;
				iCountdownSeconds = 10;
				++iSimulations;
				clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
				randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_S) {
				bPatternIsStable = false;
				iTotalPatternCounter = 0;
				iGenerations = 0;
				iSecondsRunning = 0;
				iCountdownSeconds = 10;
				iLifeScarcity = randr(iLifeMin, iLifeMax);
				++iSimulations;
				clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
				randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);				
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_M) {
				bPatternIsStable = false;
				iTotalPatternCounter = 0;
				iGenerations = 0;
				iSecondsRunning = 0;
				iCountdownSeconds = 10;
				iLifeScarcity = iLifeMin;
				++iSimulations;
				clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
				randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_N) {
				bPatternIsStable = false;
				iTotalPatternCounter = 0;
				iGenerations = 0;
				iSecondsRunning = 0;
				iCountdownSeconds = 10;
				iLifeScarcity = iLifeMax;
				++iSimulations;
				clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
				randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);
			}

			if (oEvent.keyboard.keycode == ALLEGRO_KEY_F) {
				++iFPS;				
				al_set_timer_speed(pTimer, (1.0f / iFPS));
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_G) {
				if(iFPS > 3) {
					--iFPS;
				}
				al_set_timer_speed(pTimer, (1.0f / iFPS));
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_C) {				
				int iRCell = randr(0, 255);
				int iGCell = randr(0, 255);
				int iBCell = randr(0, 255);
				oCellColor = al_map_rgb(iRCell, iGCell, iBCell);
			}
		}

	}	// End main loop

	al_destroy_event_queue(pQueue);	
	al_destroy_display(pDisplay);

	delete iTotalPatternStable;
	for (short int i = 0; i < iAppWidth; i++) {
		delete pCells[i];
		delete pNextGenCells[i];
	}
	delete[] pCells;
	delete[] pNextGenCells;
	return 0;
}
示例#8
0
LifeDialog::LifeDialog( int scale, QWidget * parent, const char * name )
    : QWidget( parent, name )
{
    qb = new QPushButton( "Quit!", this );
    cb = new QComboBox( this, "comboBox" );
    life = new LifeWidget(scale, this);
    life->move( SIDEBORDER, TOPBORDER );


    connect( qb, SIGNAL(clicked()), qApp, SLOT(quit()) );
    qb->setGeometry( SIDEBORDER, SIDEBORDER, qb->sizeHint().width(), 25 );
    timer = new LifeTimer( this );

    connect( timer, SIGNAL(timeout()), life, SLOT(nextGeneration()) );
    pb = new QPushButton( "Pause", this );
    pb->setToggleButton( TRUE );
    connect( pb, SIGNAL(toggled(bool)), timer, SLOT(pause(bool)) );
    pb->resize( pb->sizeHint().width(), 25 );
    pb->move( width() - SIDEBORDER - pb->width(), SIDEBORDER );

    sp = new QLabel( "Speed:", this );
    sp->adjustSize();
    sp->move( SIDEBORDER, 45 );
    scroll = new QSlider( 0, LifeTimer::MAXSPEED, 50,
			     LifeTimer::MAXSPEED / 2,
			     QSlider::Horizontal, this );
    connect( scroll, SIGNAL(valueChanged(int)),
	     timer,  SLOT(setSpeed(int)) );

    scroll->move( sp->width() + 2 * SIDEBORDER, 45 );
    scroll->resize( 200, 15 );

    life->setFrameStyle( QFrame::Panel | QFrame::Sunken );
    life->show();

    srand( QTime(0,0,0).msecsTo(QTime::currentTime()) );
    int sel =  rand() % NPATS;
    getPattern( sel );

    cb->move( 2*SIDEBORDER + qb->width(), SIDEBORDER);
    cb->insertItem( "Glider Gun " );
    cb->insertItem( "Figure Eight " );
    cb->insertItem( "Pulsar " );
    cb->insertItem( "Barber Pole P2 " );
    cb->insertItem( "Achim P5 " );
    cb->insertItem( "Hertz P4 " );
    cb->insertItem( "Tumbler " );
    cb->insertItem( "Pulse1 P4" );
    cb->insertItem( "Shining Flower P5 " );
    cb->insertItem( "Pulse2 P6 " );
    cb->insertItem( "Pinwheel, Clock P4 " );
    cb->insertItem( "Pentadecatholon " );
    cb->insertItem( "Piston " );
    cb->insertItem( "Piston2 " );
    cb->insertItem( "Switch Engine " );
    cb->insertItem( "Gears (Gear, Flywheel, Blinker) " );
    cb->insertItem( "Turbine8 " );
    cb->insertItem( "P16 " );
    cb->insertItem( "Puffer " );
    cb->insertItem( "Escort " );
    cb->insertItem( "Dart Speed 1/3 " );
    cb->insertItem( "Period 4 Speed 1/2 " );
    cb->insertItem( "Another Period 4 Speed 1/2 " );
    cb->insertItem( "Smallest Known Period 3 Spaceship Speed 1/3 " );
    cb->insertItem( "Turtle Speed 1/3 " );
    cb->insertItem( "Smallest Known Period 5 Speed 2/5 " );
    cb->insertItem( "Sym Puffer " );
    cb->insertItem( "], Near Ship, Pi Heptomino " );
    cb->insertItem( "R Pentomino " );
    cb->setAutoResize( FALSE );
    cb->setCurrentItem( sel );
    cb->show();
    connect( cb, SIGNAL(activated(int)), SLOT(getPattern(int)) );

    QSize s;
    s = life->minimumSize();
    setMinimumSize( s.width() + 2 * SIDEBORDER, 
		    s.height() + TOPBORDER + SIDEBORDER );
    s = life->maximumSize();
    setMaximumSize( s.width() + 2 * SIDEBORDER, 
		    s.height() + TOPBORDER + SIDEBORDER );
    s = life->sizeIncrement();
    setSizeIncrement( s.width(), s.height() );

    resize( QMIN(512, qApp->desktop()->width()),
	    QMIN(480, qApp->desktop()->height()) );
}
void CGeneticStrategyCLv2::run()
{
    nextGeneration( m_pRandom.get() );
}