CAddrInfo CAddrMan::Select_(bool newOnly) { if (size() == 0) return CAddrInfo(); if (newOnly && nNew == 0) return CAddrInfo(); // Use a 50% chance for choosing between tried and new table entries. if (!newOnly && (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) { // use a tried node double fChanceFactor = 1.0; while (1) { int nKBucket = RandomInt(ADDRMAN_TRIED_BUCKET_COUNT); int nKBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvTried[nKBucket][nKBucketPos] == -1) { nKBucket = (nKBucket + insecure_rand.randbits(ADDRMAN_TRIED_BUCKET_COUNT_LOG2)) % ADDRMAN_TRIED_BUCKET_COUNT; nKBucketPos = (nKBucketPos + insecure_rand.randbits(ADDRMAN_BUCKET_SIZE_LOG2)) % ADDRMAN_BUCKET_SIZE; } int nId = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } else { // use a new node double fChanceFactor = 1.0; while (1) { int nUBucket = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvNew[nUBucket][nUBucketPos] == -1) { nUBucket = (nUBucket + insecure_rand.randbits(ADDRMAN_NEW_BUCKET_COUNT_LOG2)) % ADDRMAN_NEW_BUCKET_COUNT; nUBucketPos = (nUBucketPos + insecure_rand.randbits(ADDRMAN_BUCKET_SIZE_LOG2)) % ADDRMAN_BUCKET_SIZE; } int nId = vvNew[nUBucket][nUBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } }
// push_front, rotate the items void TestStress3(int size) { std::cout << "\nTestStress3..." << std::endl; CS170::List<int> list; for (int i = 0; i < size; i++) list.push_front(RandomInt(1, 9)); //std::cout << list; for (int i = 0; i < size; i++) { list.push_back(list.front()); list.pop_front(); //std::cout << list; } //std::cout << list; std::cout << "Items in the list: " << list.size() << std::endl; std::cout << std::endl; }
void valiant_torus( const Router_gpgpu *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ) { int out_port; int vc_min, vc_max; outputs->Clear( ); if ( in_channel == 2*gN ) { f->ph = 1; // Phase 1 f->intm = RandomInt( gNodes - 1 ); } if ( ( f->ph == 1 ) && ( r->GetID( ) == f->intm ) ) { f->ph = 2; // Go to phase 2 in_channel = 2*gN; // ensures correct vc selection at the beginning of phase 2 } if ( f->ph == 1 ) { // In phase 1 dor_next_torus( r->GetID( ), f->intm, in_channel, &out_port, &f->ring_par, false ); if ( f->ring_par == 0 ) { vc_min = 0; vc_max = gNumVCS/4 - 1; } else { vc_min = gNumVCS/4; vc_max = gNumVCS/2 - 1; } } else { // In phase 2 dor_next_torus( r->GetID( ), f->dest, in_channel, &out_port, &f->ring_par, false ); if ( f->ring_par == 0 ) { vc_min = gNumVCS/2; vc_max = (3*gNumVCS)/4 - 1; } else { vc_min = (3*gNumVCS)/4; vc_max = gNumVCS - 1; } } outputs->AddRange( out_port, vc_min, vc_max ); }
void CEnemy::Die(void) { int random = RandomInt( 0, 5 ); if( random == 2 ) { GAME->SlowDownFreakingTimeBro(); CCameraControl::GetInstance()->SetKillCam(true); } //do we get a potion?!? if(rand()%15 == 0) { CPlayer::GetInstance()->AcquirePotion(); AUDIO->SFXPlaySound(m_nGetPotionSound); } CBaseCharacter::Die(); m_dwDeadTimeStamp = timeGetTime(); }
void Population::Mutation(void) { unsigned int index; std::default_random_engine gen; std::uniform_int_distribution<int> distrib('a', 'z'); std::uniform_real_distribution<double> distrib_d(0,1); std::vector<char> genes; for (std::list<Chromosome *>::iterator it = _samples.begin(); it != _samples.end(); ++it) { if (distrib_d(gen) <= _mutation_rate) { index = RandomInt(0, _gene_size); genes = (*it)->getGenes(); genes[index] = (char)distrib(gen); (*it)->setGenes(genes); } } }
int ChaosRouter::_InputForOutput( int output ) const { // return an input that prefers this output int input; int offset = RandomInt( _inputs - 1 ); bool match = false; for ( int i = 0; ( i < _inputs ) && ( !match ); ++i ) { input = ( i + offset ) % _inputs; if ( _InputReady( input ) && ( ! _input_route[input]->OutputEmpty( output ) ) ) { match = true; } } return match ? input : -1; }
void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr) { unsigned int nNodes = ADDRMAN_GETADDR_MAX_PCT * vRandom.size() / 100; if (nNodes > ADDRMAN_GETADDR_MAX) nNodes = ADDRMAN_GETADDR_MAX; for (unsigned int n = 0; n < vRandom.size(); n++) { if (vAddr.size() >= nNodes) break; int nRndPos = RandomInt(vRandom.size() - n) + n; SwapRandom(n, nRndPos); assert(mapInfo.count(vRandom[n]) == 1); const CAddrInfo& ai = mapInfo[vRandom[n]]; if (!ai.IsTerrible()) vAddr.push_back(ai); } }
void game_loop(int low, int high) { int input; do { int number = RandomInt(low, high); int counter = 1; /* Initial setup */ do { printf("Guess the number I'm thinking of (between %d and %d, " "0 = quit): ", low, high); input = get_input(low, high); } while (input != 0 && input == -1); while (input != number && input != 0) { if (number < input) { printf("Too high. Guess again: "); } else if (number > input) { printf("Too low. Guess again: "); } input = get_input(low, high); ++counter; } if (input) { printf("You guessed the number in %d tries!\n", counter); printf("Play again? (1=yes, 0=no): "); scanf("%d", &input); myfflush(); } } while (input); }
inline Direction GetRandomCardinalDirection() { int randomCardinalDir = RandomInt(0, 3); switch (randomCardinalDir) { case 0: return EAST; break; case 1: return WEST; break; case 2: return SOUTH; break; case 3: return NORTH; break; default: return EAST; } }
CAddrInfo CAddrMan::Select_(bool newOnly) { if (size() == 0) return CAddrInfo(); if (newOnly && nNew == 0) return CAddrInfo(); if (!newOnly && (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) { double fChanceFactor = 1.0; while (1) { int nKBucket = RandomInt(ADDRMAN_TRIED_BUCKET_COUNT); int nKBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvTried[nKBucket][nKBucketPos] == -1) { nKBucket = (nKBucket + insecure_rand()) % ADDRMAN_TRIED_BUCKET_COUNT; nKBucketPos = (nKBucketPos + insecure_rand()) % ADDRMAN_BUCKET_SIZE; } int nId = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } else { double fChanceFactor = 1.0; while (1) { int nUBucket = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvNew[nUBucket][nUBucketPos] == -1) { nUBucket = (nUBucket + insecure_rand()) % ADDRMAN_NEW_BUCKET_COUNT; nUBucketPos = (nUBucketPos + insecure_rand()) % ADDRMAN_BUCKET_SIZE; } int nId = vvNew[nUBucket][nUBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } }
void TransactionHandler::callRandom(const unsigned int pTimes) { //std::lock_guard<std::mutex> locker(m); size_t s = mTransactions.size(); if (s > 0) { for (int i = 0; i < pTimes; i++) { //m.lock(); int random = RandomInt((int)mTransactions.size()); Transaction* t = new Transaction(mTransactions[random]); t->call(); //local variable delete t; //m.unlock(); //mTransactions[random].call(); } } }
void CAddrMan::Good_(const CService& addr, int64_t nTime) { int nId; nLastGood = nTime; CAddrInfo* pinfo = Find(addr, &nId); if (!pinfo) return; CAddrInfo& info = *pinfo; if (info != addr) return; info.nLastSuccess = nTime; info.nLastTry = nTime; info.nAttempts = 0; if (info.fInTried) return; int nRnd = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucket = -1; for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT; int nBpos = info.GetBucketPosition(nKey, true, nB); if (vvNew[nB][nBpos] == nId) { nUBucket = nB; break; } } if (nUBucket == -1) return; LogPrint("addrman", "Moving %s to tried\n", addr.ToString()); MakeTried(info, nId); }
int SelectWeightedSequence( CStudioHdr *pstudiohdr, int activity, int curSequence ) { VPROF( "SelectWeightedSequence" ); if (! pstudiohdr) return 0; if (!pstudiohdr->SequencesAvailable()) return 0; VerifySequenceIndex( pstudiohdr ); int weighttotal = 0; int seq = ACTIVITY_NOT_AVAILABLE; int weight = 0; for (int i = 0; i < pstudiohdr->GetNumSeq(); i++) { int curActivity = GetSequenceActivity( pstudiohdr, i, &weight ); if (curActivity == activity) { if ( curSequence == i && weight < 0 ) { seq = i; break; } weighttotal += iabs(weight); int randomValue; if ( IsInPrediction() ) randomValue = SharedRandomInt( "SelectWeightedSequence", 0, weighttotal - 1, i ); else randomValue = RandomInt( 0, weighttotal - 1 ); if (!weighttotal || randomValue < iabs(weight)) seq = i; } } return seq; }
DETOUR_DECL_MEMBER(ActionResult<CTFBot>, CTFBotMvMEngineerIdle_Update, CTFBot *actor, float dt) { SCOPED_INCREMENT(rc_CTFBotMvMEngineerIdle_Update); TRACE(); static IntervalTimer last_ask; constexpr float ask_interval = 20.0f; constexpr float ask_minwait = 3.0f; if (RandomFloat(0.0f, 1.0f) < (dt / ask_interval)) { if (last_ask.GetElapsedTime() > ask_minwait) { last_ask.Start(); switch (RandomInt(0, 2)) { case 0: case 1: actor->SpeakConceptIfAllowed(MP_CONCEPT_PLAYER_TELEPORTERHERE); break; case 2: actor->SpeakConceptIfAllowed(MP_CONCEPT_PLAYER_SENTRYHERE); break; } } } auto result = DETOUR_MEMBER_CALL(CTFBotMvMEngineerIdle_Update)(actor, dt); if (result.transition == ActionTransition::SUSPEND_FOR && result.action != nullptr) { if (strcmp(result.action->GetName(), "MvMEngineerBuildSentryGun") == 0 && hint_sg != nullptr) { delete result.action; result.action = new CTFBotMvMEngineerBuildSGDispenser(hint_sg); hint_sg = nullptr; } else if (strcmp(result.action->GetName(), "MvMEngineerBuildTeleportExit") == 0 && hint_te != nullptr) { delete result.action; result.action = new CTFBotMvMEngineerBuildTEDispenser(hint_te); hint_te = nullptr; } } return result; }
void CASW_Video::OnVideoOver() { if ( m_bIsTransition ) { m_bIsTransition = false; BeginPlayback( m_nLastTempVideo ); } else if ( !m_bIsLoopVideo ) { m_bIsLoopVideo = true; BeginPlayback( m_nLoopVideo ); } else if ( m_nNumLoopAlternatives > 0 && RandomFloat() < m_fAlternateChance ) { PlayTempVideo( m_nLoopVideo + RandomInt( 1, m_nNumLoopAlternatives ) ); } else { bik->SetFrame( GetVideoFaceBIKHandles()->GetBIKHandle( m_nLoopVideo ), 0.0f ); } }
// push_front, subscript void TestStress4(int size, int value) { std::cout << "\nTestStress4..." << std::endl; CS170::List list; for (int i = 0; i < size; i++) list.push_front(RandomInt(1, 9)); //std::cout << list; int count = 0; for (int i = 0; i < size; i++) { if (list[i] == value) count++; } std::cout << "Items in the list: " << list.size() << std::endl; std::cout << "The number " << value << " appears " << count << " times in the list" << std::endl; std::cout << std::endl; }
int HotSpotTrafficPattern::dest(int source) { assert((source >= 0) && (source < _nodes)); if(_hotspots.size() == 1) { return _hotspots[0]; } int pct = RandomInt(_max_val); for(size_t i = 0; i < (_hotspots.size() - 1); ++i) { int const limit = _rates[i]; if(limit > pct) { return _hotspots[i]; } else { pct -= limit; } } assert(_rates.back() > pct); return _hotspots.back(); }
void CTF2UpgradeObjectEvent::Execute(IBotEventInterface *pEvent) { if (bot_use_vc_commands.GetBool() && RandomInt(0, 1)) { eEngiBuild object = (eEngiBuild)pEvent->GetInt("object", 0); bool isbuilder = (pEvent->GetInt("isbuilder") > 0); short index = pEvent->GetInt("index"); if (!isbuilder) { // see if builder is a bot edict_t *pOwner = CTeamFortress2Mod::GetBuildingOwner(object, index); CBotTF2 *pBot; if ((pBot = (CBotTF2*)CBots::GetBotPointer(pOwner)) != NULL) { pBot->AddVoiceCommand(TF_VC_THANKS); } } } }
void Powerup::manifest (void) { if (random) { type = RandomInt (0, MAX_POWERUP); } SetModel (models[type]); RemoveEffects (EF_NODRAW); SetSolid (SOLID_BBOX); AddSolidFlags (FSOLID_TRIGGER); SetMoveType (MOVETYPE_NONE); UTIL_SetSize (this, -Vector (32,32,32), Vector (32,32,32)); SetThink (NULL); SetTouch (&Powerup::pickup); CPASFilter filter (GetAbsOrigin ()); filter.UsePredictionRules (); EmitSound (filter, entindex (), "Item.Materialize"); }
// picks a number of spawners randomly from this spawngroup void CASW_Spawn_Group::PickSpawnersRandomly( int nNumSpawners, bool bIncludeRecentlySpawned, CUtlVector< CASW_Base_Spawner* > *pSpawners ) { pSpawners->RemoveAll(); CUtlVector< CASW_Base_Spawner* > candidates; for ( int i = 0; i < m_hSpawners.Count(); i++ ) { if ( !m_hSpawners[i].Get() || !m_hSpawners[i]->IsEnabled() ) continue; if ( !bIncludeRecentlySpawned && m_hSpawners[i]->HasRecentlySpawned() ) continue; candidates.AddToTail( m_hSpawners[i].Get() ); } for ( int i = 0; ( (i < nNumSpawners) && (candidates.Count() > 0) ); i++ ) { int nChosen = RandomInt( 0, candidates.Count() - 1 ); pSpawners->AddToTail( candidates[ nChosen ] ); candidates.Remove( nChosen ); } }
void Population::Selection(void) { unsigned int nbSelected = 0; unsigned int nbChild = _size * _selection_rate; std::list<Chromosome *> list; if (_samples.size() > 0) { _parents.clear(); while (nbSelected < nbChild) { for (unsigned int i = 0; i < 2; i++) { for (unsigned int i = 0; i < _pool_size; i++) list.push_back(getChromosomesByIdx(_samples, RandomInt(0, _size))); list.sort(&CompareChromosomes); _parents.push_back(list.front()); list.clear(); } nbSelected++; } } }
void test4() { PlatformRandom random; SecTimer timer; for(ulen cnt=1;;cnt++) { Printf(Con,"cnt = #;\r",cnt); Int P=RandomInt(32,random); if( P<0 ) P=-P; if( P.isEven() ) P=P+1; if( Math::NoPrimeTest<Int>::RandomTest(P,30,random) ) { Printf(Con,"\ntime = #;\nP = #;\nbits = #;\n",PrintTime(timer.get()),P,P.bitsOf().total()); return; } } }
void DispatchGibParticle( C_BaseAnimating *pEntity, const char *pszBone, bool bExplosion, int iBloodType ) { if ( iBloodType != BLOOD_COLOR_RED ) return; if ( pszBone == NULL ) return; const char *pszParticle = "blood_advisor_puncture_withdraw"; if ( bExplosion ) { const char *pszExplosionParticles[] = { "blood_advisor_spray_strong", "blood_advisor_spray_strong_2", "blood_advisor_spray_strong_3", }; pszParticle = pszExplosionParticles[ RandomInt( 0, ARRAYSIZE( pszExplosionParticles ) - 1 ) ]; } DispatchParticleEffect( pszParticle, PATTACH_BONE_FOLLOW, pEntity, pszBone ); }
void WeaponManager_AmmoMod( CBaseCombatWeapon *pWeapon ) { for ( int i = 0; i < g_Managers.Count(); i++ ) { if ( g_Managers[i]->m_iszWeaponName == pWeapon->m_iClassname ) { int iNewClip = (int)(pWeapon->m_iClip1 * g_Managers[i]->m_flAmmoMod); int iNewRandomClip = iNewClip + RandomInt( -2, 2 ); if ( iNewRandomClip > pWeapon->GetMaxClip1() ) { iNewRandomClip = pWeapon->GetMaxClip1(); } else if ( iNewRandomClip <= 0 ) { //Drop at least one bullet. iNewRandomClip = 1; } pWeapon->m_iClip1 = iNewRandomClip; } } }
void CMenuMarcher::Speak() { if (GameServer()->GetGameTime() < m_flNextSpeech) return; m_flNextSpeech = GameServer()->GetGameTime() + RandomFloat(5, 10); if (rand()%6 != 0) return; const char* apszTankLines[] = { "^.^", "<3", ":D!", "\\o/", ">D", "8)", "!!", }; DigitanksGame()->TankSpeak(this, apszTankLines[RandomInt(0, 6)]); }
//----------------------------------------------------------------------------- // We're taking cover from danger //----------------------------------------------------------------------------- void CAI_PolicingBehavior::AnnouncePolicing( void ) { // We're policing static const char *pWarnings[3] = { "METROPOLICE_MOVE_ALONG_A", "METROPOLICE_MOVE_ALONG_B", "METROPOLICE_MOVE_ALONG_C", }; if ( m_nNumWarnings <= 3 ) { HostSpeakSentence( pWarnings[ m_nNumWarnings - 1 ], SENTENCE_PRIORITY_MEDIUM, SENTENCE_CRITERIA_NORMAL ); } else { // We loop at m_nNumWarnings == 4 for players who aren't moving // but still pissing us off, and we're not allowed to do anything about it. (i.e. can't leave post) // First two sentences sound pretty good, so randomly pick one of them. int iSentence = RandomInt( 0, 1 ); HostSpeakSentence( pWarnings[ iSentence ], SENTENCE_PRIORITY_MEDIUM, SENTENCE_CRITERIA_NORMAL ); } }
// Improved Roulette Wheel // Mathematically computes the index into a large array and // selects the correct element from the small array int ChooseParent() { int randSelector = (int)RandomFloat(0, sumFitness) * 100; // Translate this number to the corresponding member** int memberID = 0; int partialSum = 0; for (int i = 0; i < population.size(); i++) { int n = (int)(population[i]->fitness * 100); if (partialSum < randSelector && partialSum + n >= randSelector) { return i; } partialSum += n; /* for (int j = 0; j < n; j++) { partialSum += 1; if (partialSum == randSelector) { return i; } }*/ } int alternate = RandomInt(0, 99); return this->best_index; /*while (randSelector > partialSum) { partialSum += population[memberID]->fitness;// / sumFitness;// fitness(memberID); memberID++; }*/ //return memberID; }
bool CCPU::BeginConstruction() { if (!IsPreviewBuildValid()) return false; if (GetPowerToConstruct(m_ePreviewStructure, GetPreviewBuild()) > GetDigitanksPlayer()->GetPower()) return false; CNetworkParameters p; p.ui1 = GetHandle(); p.i2 = m_ePreviewStructure; p.fl3 = GetPreviewBuild().x; p.fl4 = GetPreviewBuild().y; p.fl5 = GetPreviewBuild().z; if (GameNetwork()->IsHost()) BeginConstruction(&p); else GameNetwork()->CallFunctionParameters(NETWORK_TOSERVER, "BeginConstruction", &p); bool bSuccess = false; // This is used for the bot to see if a build was successful. if (GameNetwork()->IsHost()) bSuccess = (p.ui1 != ~0); else bSuccess = true; if (bSuccess && GetDigitanksPlayer()) { int iRunners = RandomInt(15, 10); for (int i = 0; i < iRunners; i++) DigitanksGame()->GetTerrain()->AddRunner(GetPreviewBuild(), GetDigitanksPlayer()->GetColor(), 1); } return bSuccess; }
void CASW_Director::OnMissionStarted() { // if we have wanders turned on, spawn a couple of encounters if ( asw_wanderer_override.GetBool() && ASWGameRules() ) { ASWSpawnManager()->SpawnRandomShieldbug(); int nParasites = 1; switch( ASWGameRules()->GetSkillLevel() ) { case 1: nParasites = RandomInt( 4, 6 ); break; default: case 2: nParasites = RandomInt( 4, 6 ); break; case 3: nParasites = RandomInt( 5, 7 ); break; case 4: nParasites = RandomInt( 5, 9 ); break; case 5: nParasites = RandomInt( 5, 10 ); break; } while ( nParasites > 0 ) { int nParasitesInThisPack = RandomInt( 3, 6 ); if ( ASWSpawnManager()->SpawnRandomParasitePack( nParasitesInThisPack ) ) { nParasites -= nParasitesInThisPack; } else { break; } } } if (ASWGameRules()->m_iPrespawnScale) { // spawn random parasites 7, boomers 3, mortars 3, harvesters 4, // drones 15, uber drones 2, shieldbug 1, shaman 7, flies 3 ASWSpawnManager()->PrespawnAliens(ASWGameRules()->m_iPrespawnScale); // get num nodes // get random node // check if it's far enough from player start, 1000 units // check if valid spawn point for an alien // spawn alien } }
void Test_RandomizeInPVS( const CCommand &args ) { if ( args.ArgC() < 2 ) { Error( "Test_RandomizeInPVS <percentage chance to change>" ); } int percent = atoi( args[ 1 ] ); for ( int i=0; i < g_StressEntities.Count(); i++ ) { CBaseEntity *pEnt = g_StressEntities[i]; if ( pEnt ) { if ( RandomInt( 0, 100 ) < percent ) { if ( pEnt->IsEffectActive( EF_NODRAW ) ) pEnt->RemoveEffects( EF_NODRAW ); else pEnt->AddEffects( EF_NODRAW ); } } } }