void CAsteroid::Init(EAsteroidType type) { m_State = AS_NONE; m_Type = type; m_Pos.Zero(); m_Vel.Zero(); m_Rot = RandFloat(0.0f, 360.0f); m_RotVel= RandFloat(-100.0f, 100.0f); m_Time = 0.0f; if (type == AT_BIG) m_Size = RandFloat(25.0f, 35.0f); else m_Size = RandFloat(5.0f, 15.0f); // Create the asteroid by forming a circle that we randomize a bit f32 rot = 0.0f; CVector2 prev(0.0f, 0.0f); for (int lNr=0; lNr<ASTEROIDNUMLINES; lNr++) { CVector2 v = CVector2(0.0f, m_Size*RandFloat(0.7f, 1.0f)).Rotate((f32)(lNr+1)*(360.0f/(f32)ASTEROIDNUMLINES)); m_Lines[lNr][0] = prev; m_Lines[lNr][1] = v; prev = v; } m_Lines[0][0] = m_Lines[ASTEROIDNUMLINES-1][1]; }
//-------------------------------------------Reset()-------------------- // // Resets the sweepers position, MinesGathered and rotation // //---------------------------------------------------------------------- void CMinesweeper::Reset(vector<CCollisionObject> &objects) { double threshold = (CParams::dMineScale+5)*(CParams::dMineScale+5); boolean collision = false; do{ //reset the sweepers positions but don't spawn on mines m_vPosition = SVector2D((RandFloat() * CParams::WindowWidth), (RandFloat() * CParams::WindowHeight)); collision = false; for(int i=0; i < objects.size(); i++){ if(objects[i].getType() == CCollisionObject::SuperMine){ if(Vec2DLengthSquared(m_vPosition-objects[i].getPosition()) <= threshold){ collision = true; break; } } } }while(collision); //and the MinesGathered m_dMinesGathered = 0; m_dSuperMinesGathered = 0; //and the rotation m_dRotation = RandFloat()*CParams::dTwoPi; minesLeft = minesRight = minesForwardLeft = minesForwardRight = false; return; }
//------------------------------- MutateWeights--------------------------- // Iterates through the genes and purturbs the weights given a // probability mut_rate. // // prob_new_mut is the chance that a weight may get replaced by a // completely new weight. // // dMaxPertubation is the maximum perturbation to be applied. // // type is the type of random number algorithm we use //------------------------------------------------------------------------ void CGenome::MutateWeights(double mut_rate, double prob_new_mut, double MaxPertubation) { for (int cGen=0; cGen<m_vecLinks.size(); ++cGen) { //do we mutate this gene? if (RandFloat() < mut_rate) { //do we change the weight to a completely new weight? if (RandFloat() < prob_new_mut) { //change the weight using the random distribtion defined by 'type' m_vecLinks[cGen].dWeight = RandomClamped(); } else { //perturb the weight m_vecLinks[cGen].dWeight += RandomClamped() * MaxPertubation; } } } return; }
void SceneController::updateSimulationOpenMP() { // NN uses STL (it's not ported into the QTL) auto mines = vecMines.toStdVector(); #pragma omp parallel for for (int i = 0; i < vecSweepers.size(); ++i) { int grabHit; // update the NN and position if (!vecSweepers[i].Update(mines)) { // error in processing the neural net gsInfo->setText("ERROR: Wrong amount of NN inputs!"); m_bInternalError = true; continue; } // keep minesweepers in our viewport vecSweepers[i].WarpWorld(0, 0, vpWidth, vpHeight); #pragma omp critical // see if it's found a mine if ((grabHit = vecSweepers[i].CheckForMine(mines, MainWindow::s.dMineScale)) != -1) { // mine found so replace the mine with another at a random position vecMines[grabHit] = SVector2D(RandFloat() * vpWidth, RandFloat() * vpHeight); // we have discovered a mine so increase fitness vecSweepers[i].IncrementFitness(); } // update the chromos fitness score vecThePopulation[i].dFitness = vecSweepers[i].Fitness(); } }
void G_DeflectMissile( gentity_t *ent, gentity_t *missile, vec3_t forward ) { vec3_t bounce_dir; int i; float speed; int isowner = 0; vec3_t missile_dir; //[MoreRandom] //[/MoreRandom] if (missile->r.ownerNum == ent->s.number) { //the original owner is bouncing the missile, so don't try to bounce it back at him isowner = 1; } //save the original speed speed = VectorNormalize( missile->s.pos.trDelta ); if (ent->client) { //VectorSubtract( ent->r.currentOrigin, missile->r.currentOrigin, missile_dir ); AngleVectors(ent->client->ps.viewangles, missile_dir, 0, 0); VectorCopy(missile_dir, bounce_dir); //VectorCopy( missile->s.pos.trDelta, bounce_dir ); VectorScale( bounce_dir, DotProduct( forward, missile_dir ), bounce_dir ); VectorNormalize( bounce_dir ); } else { VectorCopy(forward, bounce_dir); VectorNormalize(bounce_dir); } for ( i = 0; i < 3; i++ ) { //1.3 if((ent->client->pers.cmd.buttons & BUTTON_ATTACK) && ent->client->ps.fd.saberAnimLevel != SS_FAST && ent->client->ps.fd.saberAnimLevel != SS_MEDIUM && ent->client->ps.fd.saberAnimLevel != SS_TAVION) if(ent->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]==FORCE_LEVEL_3) bounce_dir[i] += RandFloat( -0.1f, 0.2f ); else if(ent->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]==FORCE_LEVEL_2) bounce_dir[i] += RandFloat( -0.2f, 0.3f ); else bounce_dir[i] += RandFloat( -0.3f, 0.4f ); else bounce_dir[i] += RandFloat( -1.0f, 1.0f ); } VectorNormalize( bounce_dir ); VectorScale( bounce_dir, speed, missile->s.pos.trDelta ); missile->s.pos.trTime = level.time; // move a bit on the very first frame VectorCopy( missile->r.currentOrigin, missile->s.pos.trBase ); if ( missile->s.weapon != WP_SABER && missile->s.weapon != G2_MODEL_PART ) { //you are mine, now! missile->r.ownerNum = ent->s.number; } if ( missile->s.weapon == WP_ROCKET_LAUNCHER ) { //stop homing missile->think = 0; missile->nextthink = 0; } }
CColumn::CColumn() { m_NumChars = 0; m_Chars = null; m_Delay = m_CharDelay = RandFloat(gConfig.m_CharDelayMin, gConfig.m_CharDelayMax); m_FadeSpeed = RandFloat(gConfig.m_FadeSpeedMin, gConfig.m_FadeSpeedMax); m_CurChar = 0; }
//---------------------------------------:move bool Puck::update() { //Update Times float diffTime, currTime; currTime = timeGetTime()/1000.0; diffTime = currTime - t_lastUpdate; t_lastUpdate = currTime; if(goal) // if goal wait for goalsplash then countdown to start new match { if(--goalCountDown<= 0) { newMatch(); goal = false; } } if(--startCountDown==0) speed= SPEED; else if(startCountDown <0) speed += 0.001; else speed = 0.0; /* Update Puck Position */ position[0] += velocity[0]*speed*diffTime; position[2] += velocity[2]*speed*diffTime; /// calculate the reflection here... // bounce off imaginary walls so puck is channelled nicely from player to player // LEFT if(position[0]-radius <= -WALLX){ position[0] = -WALLX+radius; velocity[0] = -(velocity[0])+(0.2*RandFloat()-0.1); velocity[2] = (velocity[2])+(0.1*RandFloat()-0.05); } // RIGHT if(position[0]+radius >= WALLX){ position[0] = WALLX-radius; velocity[0] = -(velocity[0])+(0.2*RandFloat()-0.1); velocity[2] = (velocity[2])+(0.1*RandFloat()-0.05); } if(!goal && goalScored()) { goal = true; speed = 0.0; startCountDown = goalCountDown = 130; } // adjust translation matrix appropriately updatePosition(); return goal; }
bool Puck::goalScored() { bool result = false; // check behind player 2 if(position[2]-radius <= -WALLZ) { position[2] = -WALLZ+radius; velocity[0] = (velocity[0])+(0.2*RandFloat()-0.1); velocity[2] = -(velocity[2])+(0.1*RandFloat()-0.05); // check for goal /* if(position[0] >= -2.0 && position[0] <= 2.0) { if(players[0]->status == ACTIVE) { players[0]->score++; // otSendScoreFor(0); if(players[1]->status == ACTIVE){ // otSendScoreAgainst(1); } return true; } } */ } // check behing player 1 if(position[2]+radius >= WALLZ) { position[2] = WALLZ-radius; velocity[0] = (velocity[0])+(0.2*RandFloat()-0.1); velocity[2] = -(velocity[2])+(0.1*RandFloat()-0.05); /* velocity[2] = -(velocity[2]); velocity.normalize();*/ // check for goal /* if(position[0] >= -2.0 && position[0] <= 2.0) { if(players[1]->status == ACTIVE) { players[1]->score++; // otSendScoreFor(1); if(players[0]->status == ACTIVE){ // otSendScoreAgainst(0); } return true; } }*/ } return false; }
void NudgeBall(t_PongBall *ball, char upOrDown) { ball->xSpeed += RandFloat(-NUDGE_MAX, NUDGE_MAX); if (upOrDown) // nudge up ball->ySpeed -= RandFloat(0, NUDGE_MAX); else // nudge down ball->ySpeed += RandFloat(0, NUDGE_MAX); }
void initOptions(int n, float *price, float *strike, float *years) { srand(5347); //Generate options set for (int i = 0; i < n; i++) { price[i] = RandFloat(5.0f, 30.0f); strike[i] = RandFloat(1.0f, 100.0f); years[i] = RandFloat(0.25f, 10.0f); } }
void CController::ResetEnvironment(){ m_vecSweepers.clear(); m_vecObjects.clear(); m_NumSweepers = CParams::iNumSweepers; m_NumSuperMines = CParams::iNumSuperMines; //let's create the mine sweepers for (int i=0; i<m_NumSweepers; ++i) { m_vecSweepers.push_back(CMinesweeper()); } //initialize super mines in random positions within the application window // such that they aren't spawned on a sweeper for (int i=0; i<m_NumSuperMines; ++i) { SVector2D position; // don't spawn on sweepers. keep finding another location if they do. boolean collision = false; do{ position = SVector2D(RandFloat() * cxClient, RandFloat() * cyClient); collision = false; for(int i=0; i < m_vecSweepers.size(); i++){ if(Vec2DLengthSquared(position-m_vecSweepers[i].Position()) <= mineSpawnThreshold){ collision = true; break; } } }while(collision); m_vecObjects.push_back(CCollisionObject(CCollisionObject::SuperMine, position)); } // Spawn mines for (int i=0; i<m_NumMines; ++i) { SVector2D position; // don't spawn on super mines. boolean collision = false; do{ position = SVector2D(RandFloat() * cxClient, RandFloat() * cyClient); collision = false; for(int i=0; i < m_vecObjects.size(); i++){ if(m_vecObjects[i].getType() == CCollisionObject::SuperMine){ if(Vec2DLengthSquared(position-m_vecObjects[i].getPosition()) <= mineSpawnThreshold){ collision = true; break; } } } }while(collision); m_vecObjects.push_back(CCollisionObject(CCollisionObject::Mine, position)); } }
// Initialize the sweepers, their brains and the GA factory. SceneController::SceneController(int width, int height, QObject *parent) : QObject(parent), gs(new QGraphicsScene(0, 0, width, height)), gsInfo(new QGraphicsSimpleTextItem), gsDefaultPen(), gsElitePen(Qt::red), gsMinePen(Qt::green), vpWidth(width), vpHeight(height), m_pGA(nullptr), m_bInternalError(false), m_iTicks(0), m_iGenerations(0) { // MSVC does not support the std::initializer_list, so this is the only way // to create our object templates and be platform independent... for (unsigned int i = 0; i < sizeof(objectMinePoints) / sizeof(*objectMinePoints); ++i) objectMine.append(objectMinePoints[i]); for (unsigned int i = 0; i < sizeof(objectSweeperPoints) / sizeof(*objectSweeperPoints); ++i) objectSweeper.append(objectSweeperPoints[i]); // compatibility mode with Qt5 gsDefaultPen.setCosmetic(true); gsElitePen.setCosmetic(true); gsMinePen.setCosmetic(true); gs->addItem(gsInfo); // let's create the minesweepers for (int i = MainWindow::s.iNumSweepers; i; --i) vecSweepers.push_back(CMinesweeper(RandFloat() * vpWidth, RandFloat() * vpHeight, RandFloat() * 2 * M_PI)); // and initial population of mines updateMineObjects(MainWindow::s.iNumMines); // get the total number of weights used in the sweepers // NN so we can initialize the GA int m_NumWeightsInNN = vecSweepers[0].GetNumberOfWeights(); // initialize the Genetic Algorithm class delete m_pGA; m_pGA = new CGenAlg(vecSweepers.size(), m_NumWeightsInNN); // get the weights from the GA and insert into the sweepers brains vecThePopulation = QVector<SGenome>::fromStdVector(m_pGA->GetChromos()); for (int i = 0; i < vecThePopulation.size(); i++) vecSweepers[i].PutWeights(vecThePopulation[i].vecWeights); }
//-------------------------------------------Reset()-------------------- // // Resets the sweepers position, fitness and rotation // //---------------------------------------------------------------------- void CMinesweeper::Reset() { //reset the sweepers positions m_vPosition = SVector2D((RandFloat() * CParams::WindowWidth), (RandFloat() * CParams::WindowHeight)); //and the fitness m_dFitness = 0; //and the rotation m_dRotation = RandFloat()*CParams::dTwoPi; return; }
void Reverb::SetTime(float s) { m_Time=s; float t=0; int count=0; for (vector<Delay*>::iterator i=m_DelayVec.begin(); i!=m_DelayVec.end(); i++) { t=count/(float)NUM_DELAYS; (*i)->SetLeftDelay(t*m_Time+RandFloat(-m_Randomness,m_Randomness)); (*i)->SetRightDelay(t*m_Time+RandFloat(-m_Randomness,m_Randomness)); count++; } }
//-----------------------------------constructor------------------------- // //----------------------------------------------------------------------- CMinesweeper::CMinesweeper(): m_dRotation(RandFloat()*CParams::dTwoPi), m_lTrack(0.16), m_rTrack(0.16), m_dFitness(0), m_dScale(CParams::iSweeperScale), m_iClosestMine(0) { //create a random start position m_vPosition = SVector2D((RandFloat() * CParams::WindowWidth), (RandFloat() * CParams::WindowHeight)); }
void Puck::newGame( void ) { Real32 r; position = Vec3f(0,puck_floor,0); goal = false; /* for(int i = 0;i<MAXPLAYERS; i++) { players[i]->score =0; }*/ /* Initialize velocity */ int rr = RandInt(10); if(rr <= 5) { r = RandFloat(); if(RandFloat() > 0.5) velocity[0] = cos(r); else velocity[0] = -cos(r); velocity[1] = 0.0; velocity[2] = -1.0; } else { r = RandFloat(); if(RandFloat() > 0.5) velocity[0] = cos(r); else velocity[0] = -cos(r); velocity[1] = 0.0; velocity[2] = 1.0; } velocity.normalize(); /* Initialize speed */ speed = SPEED; // otSendNewGame(); updatePosition(); // INITIALISE THE TIMER t_lastUpdate = timeGetTime()/1000.0; startCountDown = 100; }
void DeerGen::GenerateDeerInfo(DeerDefinition* outVal) { DeerDefinition& deer = *outVal; deer.m_isBuck = rand()%2 == 0; deer.m_age = (rand() % MAX_AGE); deer.m_weight = deer.m_isBuck ? BUCKWEIGHTS[deer.m_age] : DOEWEIGHTS[deer.m_age]; float weightRange = deer.m_weight*WEIGHT_VARIANCE; deer.m_weight += RandFloat(-weightRange, weightRange); if(deer.m_isBuck) { deer.m_rack = new RackDefinition; int basePointRange = 6 - rand()%(6 - deer.m_age); int basePointCount = 1 + (rand() % basePointRange) + deer.m_age / 2; float beamCircumference = BEAMCIRCUMFERENCE[deer.m_age]; beamCircumference += RandFloat(-beamCircumference*.2f, beamCircumference*.2f); deer.m_rack->m_width = RACKWIDTH[deer.m_age] * RandFloat(.8f, 1.25f); for(int i = 0; i < RackDefinition::AntlerSide::cCount; i++) { int pointCount = MAX(basePointCount + (rand()%4 - 2),0); float tineLength = static_cast<float>((deer.m_age + 1) * 2); tineLength *= RandFloat(.5f, 1.2f);; deer.m_rack->m_antlers[i].m_averageCircumference = beamCircumference; deer.m_rack->m_antlers[i].m_averageCircumference += RandFloat(-beamCircumference*.1f, beamCircumference*.1f); RoundToEighth(deer.m_rack->m_antlers[i].m_averageCircumference); float beamLen = BEAMLENGTHS[deer.m_age]; deer.m_rack->m_antlers[i].m_mainBeamLength = beamLen; deer.m_rack->m_antlers[i].m_mainBeamLength += RandFloat(-beamLen*.2f, beamLen*.2f); RoundToEighth(deer.m_rack->m_antlers[i].m_mainBeamLength); // brow tines float browTineLength = deer.m_age * 1.5f; browTineLength *= RandFloat(.8f,1.1f); deer.m_rack->m_antlers[i].m_tines.push_back(TineDefinition()); deer.m_rack->m_antlers[i].m_tines[0].m_length = browTineLength; deer.m_rack->m_tineCount[i]++; // main tines for(int j = 1; j < pointCount && tineLength > 0; j++) { deer.m_rack->m_antlers[i].m_tines.push_back(TineDefinition()); deer.m_rack->m_antlers[i].m_tines[j].m_length = tineLength; tineLength *= RandFloat(.75, .9f); RoundToEighth(tineLength); deer.m_rack->m_tineCount[i]++; } } deer.m_score = deer.m_rack->CalculateScore(); } }
//----------------------------Crossover-------------------------------- // Takes 2 parent vectors, selects a midpoint and then swaps the ends // of each genome creating 2 new genomes which are stored in baby1 and // baby2. //--------------------------------------------------------------------- void Cga::Crossover( const vector<int> &mum, const vector<int> &dad, vector<int> &baby1, vector<int> &baby2) { //just return parents as offspring dependent on the rate //or if parents are the same if ( (RandFloat() > m_dCrossoverRate) || (mum == dad)) { baby1 = mum; baby2 = dad; return; } //determine a crossover point int cp = RandInt(0, m_iChromoLength - 1); //swap the bits for (int i=0; i<cp; ++i) { baby1.push_back(mum[i]); baby2.push_back(dad[i]); } for (i=cp; i<mum.size(); ++i) { baby1.push_back(dad[i]); baby2.push_back(mum[i]); } }
TikiSteering::TikiSteering(TikiBot* agent) : tikiBot(agent), flags(0), weightSeparation(2.0f), weightWander(1.0f), weightWallAvoidance(10.0), viewDistance(10.0f), deceleration(normal), targetAgent1(0), targetAgent2(0), wanderDistance(WanderDist), wanderJitter(WanderJitterPerSec), wanderRadius(WanderRad), weightSeek(0.5f), weightArrive(1.0f), cellSpaceOn(false), summingMethod(prioritized) { //stuff for the wander behavior float theta = RandFloat() * TwoPi; //create a vector to a target position on the wander circle wanderTarget = Vector2(wanderRadius * cosf(theta), wanderRadius * sinf(theta)); }
//////////////////////////////////////////////////////////////////////////// // Generates a new value based on the animation mode // Will also adjust the current value if needed // void CFloatAnimator::GetNewValue(f32& fromValue, f32& toValue, f32 min, f32 max, EAMode mode) { switch (mode) { case AM_NONE: toValue = fromValue; break; case AM_RAND: toValue = min + (RandFloat()*(max-min)); break; case AM_LOOPUP: if (ISEQUAL(fromValue, max, 0.01f)) fromValue = min; toValue = max; break; case AM_LOOPDOWN: if (ISEQUAL(fromValue, min, 0.01f)) fromValue = max; toValue = min; break; case AM_PINGPONG: if (ISEQUAL(fromValue, min, 0.01f)) { toValue = max; } else { toValue = min; } break; default: break; } }
//----------------------------------GetChromoRoulette()------------------ // // returns a chromo based on roulette wheel sampling // //----------------------------------------------------------------------- SGenome CGenAlg::GetChromoRoulette() { //generate a random number between 0 & total fitness count double Slice = (double)(RandFloat() * m_dTotalFitness); //this will be set to the chosen chromosome SGenome TheChosenOne; //go through the chromosones adding up the fitness so far double FitnessSoFar = 0; for (int i=0; i<m_iPopSize; ++i) { FitnessSoFar += m_vecPop[i].dFitness; //if the fitness so far > random number return the chromo at //this point if (FitnessSoFar >= Slice) { TheChosenOne = m_vecPop[i]; break; } } return TheChosenOne; }
void WifesGlobalState::Execute(MinersWife *wife) { if(RandFloat() < 0.1) { wife->GetFSM()->ChangeState(VisitBathroom::Instance()); } }
Reverb::Reverb() : m_Time(0), m_Feedback(0.2), m_Randomness(0.01), m_Bypass(true) { // set up the delay vec for (int i=0; i<NUM_DELAYS; i++) { Delay *pDelay = new Delay; pDelay->SetLeftDelay(RandFloat(MIN_DELAYTIME,MAX_DELAYTIME)); pDelay->SetRightDelay(RandFloat(MIN_DELAYTIME,MAX_DELAYTIME)); pDelay->SetBypass(false); m_DelayVec.push_back(pDelay); } }
//-----------------------------ctor--------------------------------------- // //------------------------------------------------------------------------ CController::CController(int cxClient, int cyClient): m_bSuccess(false), m_vPadPos(SVector2D(RandFloat()*cxClient, 50)), m_cxClient(cxClient), m_cyClient(cyClient) { //create a starting postion for the landers SVector2D vStartPos = SVector2D(WINDOW_WIDTH/2, cyClient-50); //create the user controlled lander m_pUserLander = new CLander(cxClient, cyClient, PI, vStartPos, m_vPadPos); //set up the VB for the landing pad for (int i=0; i<NumPadVerts; ++i) { m_vecPadVB.push_back(Pad[i]); } //setup the stars for (int i=0; i<NumStars; ++i) { m_vecStarVB.push_back(SPoint(RandInt(0, cxClient), RandInt(100, cyClient))); } }
//------------------------- ctor ----------------------------------------- // //------------------------------------------------------------------------ SteeringBehavior::SteeringBehavior(MovingEntity* agent): m_pMovingEntity(agent), m_iFlags(0), m_dDBoxLength(10), m_dWeightWander(100), m_dWeightForward(100), m_dWeightBoundsAvoidance(400), m_dWeightObstacleAvoidance(200), m_Deceleration(normal), pursuitTarget(NULL), seekTarget(NULL), fleeTarget(NULL), hideTarget(NULL), m_dWeightSeek(100), m_dWeightFlee(100), m_dWeightArrive(100), m_dWeightPursuit(100), m_dWeightOffsetPursuit(50), m_dWeightHide(100), m_SummingMethod(weighted_average) { //create a vector to a target position on the wander circle float theta = RandFloat() * TwoPi; m_vWanderTarget = Vector2D(WanderRad * cos(theta), WanderRad * sin(theta)); }
//------------------------MutateSM-------------------------------- // // chooses a random start and point then scrambles the genes // between them //---------------------------------------------------------------- void CgaTSP::MutateSM(vector<int> &chromo) { //return dependent upon mutation rate if (RandFloat() > m_dMutationRate) return; //first we choose a section of the chromosome const int MinSpanSize = 3; //these will hold the beginning and end points of the span int beg, end; ChooseSection(beg, end, chromo.size()-1, MinSpanSize); int span = end - beg; //now we just swap randomly chosen genes with the beg/end //range a few times to scramble them int NumberOfSwapsRqd = span; while(--NumberOfSwapsRqd) { vector<int>::iterator gene1 = chromo.begin(); vector<int>::iterator gene2 = chromo.begin(); //choose two loci within the range advance(gene1, beg + RandInt(0, span)); advance(gene2, beg + RandInt(0, span)); //exchange them swap(*gene1, *gene2); }//repeat }
//-------------------------MutateDM------------------------------------- // // Select two random points, grab the chunk of chromosome between them // and then insert it back into the chromosome in a random position // displaced from the original. //---------------------------------------------------------------------- void CgaTSP::MutateDM(vector<int> &chromo) { //return dependent upon mutation rate if (RandFloat() > m_dMutationRate) return; //first we choose a section of the chromosome const int MinSpanSize = 3; //these will hold the beginning and end points of the span int beg, end; ChooseSection(beg, end, chromo.size()-1, MinSpanSize); //setup iterators for our beg/end points vector<int>::iterator SectionStart = chromo.begin() + beg; vector<int>::iterator SectionEnd = chromo.begin() + end; //hold on to the section we are moving vector<int> TheSection; TheSection.assign(SectionStart, SectionEnd); //erase from current position chromo.erase(SectionStart, SectionEnd); //move an iterator to a random insertion location vector<int>::iterator curPos; curPos = chromo.begin() + RandInt(0, chromo.size()-1); //re-insert the section chromo.insert(curPos, TheSection.begin(), TheSection.end()); }
void EnumKare::Crossover(const vector<int> &mum, const vector<int> &dad, vector<int> &baby1, vector<int> &baby2) { //由随机概率决定是否杂交,若两亲本相同也不杂交 //不杂交则直接复制亲本 if (RandFloat() > m_dCrossoverRate || mum == dad) { baby1 = dad; baby2 = mum; return; } int cp = RandInt(0, m_iChromoLength - 1); int i; for ( i = 0; i < cp; i++) { baby1.push_back(mum[i]); baby2.push_back(dad[i]); } for ( i = cp; i < mum.size(); i++) { baby1.push_back(dad[i]); baby2.push_back(mum[i]); } }
float3 UnsyncedRNG::RandVector() { #ifdef USE_BOOST_RNG float3 ret(&genSphere()[0]); ret *= RandFloat(); #else float3 ret; do { ret.x = RandFloat() * 2 - 1; ret.y = RandFloat() * 2 - 1; ret.z = RandFloat() * 2 - 1; } while (ret.SqLength() > 1); #endif return ret; }
void Controller::checkCollision() { for(int i = 0; i < CParams::iNumSweepers; i++) for(int j = 0; j < CParams::iNumMines; j++) if(mineSweepers[i]->collidesWithItem(a_mines[j])) if(a_mines[j] != NULL) { mineSweepers[i]->scene()->removeItem(a_mines[j]); double x = RandFloat() * CParams::iWindowWidth; double y = RandFloat() * CParams::iWindowHeight; a_mines[j]->setPos(x,y); v_mines[j] = SVector2D(SVector2D(x,y)); mineSweepers[i]->scene()->addItem(a_mines[j]); mineSweepers[i]->increaseFitness(1); } }