void doMutation(struct Chromosome *child){ // Mutate Chromosome int randomGene=0, randomFrom=0, randomValue=0; randomGene = ((int)((double)rand() / ((double)RAND_MAX + 1)*GENETIC_PURSUERS)); // Random number between 0 and GENETIC_PURSUERS randomFrom = ((int)((double)rand() / ((double)RAND_MAX + 1)*(*child).chrSteps));// Random step between 0 and current max steps randomValue = ((int)((double)rand() / ((double)RAND_MAX + 1)*100)); // Random number between 0 and 99 if(randomValue < GENETIC_MUTATION_PROBABILITY*100) getRandom(&(*child).gene[randomGene], randomFrom); // Generate part of new gene }
void eightBallBot::onMessage(ircMessage& msg) { std::string cmd = msg.message().substr(0, 6); if(!cmd.compare("!8ball")) { _utils->sendMessage(msg.channel(), replys[getRandom()]); } }
int getRandom(int low, int high){ int num; num = rand() % high + low; if (num > high) getRandom(low, high); else return num; }
/** * A function to return a random positive or negative 1 (+1, -1 but not 0) */ double getRandom(){ double random = rand()%3-1; if(random == 0) { random = getRandom(); } return random; }
static ssize_t random_pread(Inode *inode, File *fp, void *buffer, size_t size, off_t offset) { uint64_t *put = (uint64_t*) buffer; ssize_t out = 0; while (size >= 8) { *put++ = getRandom(); size -= 8; out += 8; }; if (size != 0) { uint64_t final = getRandom(); memcpy(put, &final, size); out += size; };
static struct pos_s getFood(void) { int i,pos; struct pos_s res; tryagain: res.x = (getRandom() % (SIZE_X-1)) + 1; res.y = (getRandom() % (SIZE_Y-3)) + 3; for(i=0; i<snake.len; i++) { pos = (snake.t_start < i) ? (MAX_SNAKE_LEN - (i-snake.t_start)) : (snake.t_start-i); if (snake.tail[pos].x == res.x && snake.tail[pos].y == res.y) // no food to be spawn in snake plz goto tryagain; } return res; }
/** reaction.c * First l0dable for my r0ket * Improvement is welcome * * AUTHOR: hubba */ void ram(void) { char x = gpioGetValue(RB_LED1); int rand_wait = 0; int react_time=0; int start_time = 0; int end_time = 0; gpioSetValue (RB_LED1,0); //upperleft LED off lcdClear(); lcdPrintln("Hello"); lcdPrintln(GLOBAL(nickname)); lcdPrintln("ReACTION"); lcdRefresh(); delayms(500); while(1) { react_time = 0; lcdPrintln("Press ENTER if "); lcdPrintln("LED is on!"); lcdRefresh(); rand_wait = getRandom(); rand_wait = rand_wait%50; rand_wait = 40 + rand_wait*4; // Minimum pause time is 400ms for(int i =0; i<=rand_wait; i++) //directly calling delayms(rand_wait) didn't work { delayms(10); } gpioSetValue (RB_LED1, 1); //upperleft LED ON getInputWaitRelease(); start_time = getTimer()*(SYSTICKSPEED); while (getInputWait() != BTN_ENTER); //wait for user input { } end_time = getTimer()*(SYSTICKSPEED); react_time = end_time - start_time; //measure used time lcdClear(); lcdPrint("Needed "); lcdPrintInt(react_time); lcdPrintln(" ms"); lcdPrintln("DOWN: Exit"); lcdPrintln("0ther: New game"); lcdRefresh(); gpioSetValue (RB_LED1,0); //upperleft LED off getInputWaitRelease(); if(getInputWait() == BTN_DOWN) //Check for Exit/new game { gpioSetValue (RB_LED1, x); //upperleft LED as before l0dable executed return; } } /* NEVER LAND HERE */ lcdPrintln("Flow-Error"); lcdRefresh(); return; };
/** * Private build method, returns 1 if success, 0 othervise * uint key: A non-negative key * uint payload: A non-negative payload * int l: Attempted insertions, has to below R */ int SplashTable::insert(uint key, uint payload, int l, int lastBucket){ int hashedValue; int minFilled = B; //Count of least filled bucket int leastFilledBucket = 0; //Index of least filled bucket int hitLastBucket = 0; //Loops through all hash functions for(int i = 0; i<h; i++){ hashedValue = hashes[i].hash(key); //Hashes key if(hashedValue == lastBucket){ hitLastBucket++; continue; } //Tests if minFilled is bigger than current bucket count if(buckets[hashedValue].count < minFilled){ minFilled = buckets[hashedValue].count; leastFilledBucket = hashedValue; } } if(minFilled == B){ // they were all full, we need to do a swap and recurse // if we've hit our recursion limit, bad news if (l==R){ return 0; } // choose a random bucket int randomBucket; do{ //Assigns a random bucket from the possible hash functions //Run only once if all hash functions hash to the same bucket //OR if found bucket is not the same as last attempt randomBucket = hashes[getRandom(0, h-1)].hash(key); } while (randomBucket == lastBucket & hitLastBucket != h); //Retrieves index of oldest bucket int index = buckets[randomBucket].getIndexOfOldest(); // swap out the old value and put in the new int tempKey = buckets[randomBucket].keys[index]; int tempPayload = buckets[randomBucket].payload[index]; //Insert the (key, payload) in the oldest bucket buckets[randomBucket].insert(key, payload); //Recursive call, increment l, return insert(tempKey, tempPayload, ++l, randomBucket); } else { // we had room, do the storage Bucket *bucket = &buckets[leastFilledBucket]; bucket->insert(key, payload); totalCount++; //increments table count return 1; } }
void runTest() { beginTest ("AbstractFifo"); int buffer [5000]; AbstractFifo fifo (numElementsInArray (buffer)); WriteThread writer (fifo, buffer, getRandom()); int n = 0; Random r = getRandom(); r.combineSeed (12345); for (int count = 100000; --count >= 0;) { int num = r.nextInt (6000) + 1; int start1, size1, start2, size2; fifo.prepareToRead (num, start1, size1, start2, size2); if (! (size1 >= 0 && size2 >= 0) && (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize())) && (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()))) { expect (false, "prepareToRead returned -ve values"); break; } bool failed = false; for (int i = 0; i < size1; ++i) failed = (buffer [start1 + i] != n++) || failed; for (int i = 0; i < size2; ++i) failed = (buffer [start2 + i] != n++) || failed; if (failed) { expect (false, "read values were incorrect"); break; } fifo.finishedRead (size1 + size2); } }
// add a random elevation to create some waves void addRandomDrop() { if(getRandom()<= 0.25 * dt) { int px = getRandom() * (Real)SIZE; int py = getRandom() * (Real)SIZE; int s = getRandom() * (Real)SIZE * 0.05; Real h = getRandom(0.01, 0.07); if(s<1) s=1; for (int i=px-s; i<px+s; i++) for (int j=py-s; j<py+s; j++) { const int index = i + j*SIZE; if( i<0 || j<0 || i>(SIZE-1) || j>(SIZE-1) ) continue; eta[index] += h; if( eta[index] > 1.1) eta[index] = 1.1; } } }
void CEsdlSvcEngine::generateTransactionId(IEspContext & context, StringBuffer & trxid) { //RANDOMNUM_DATE for now. CriticalBlock b(trxIdCritSec); Owned<IJlibDateTime> _timeNow = createDateTimeNow(); SCMStringBuffer _dateString; _timeNow->getDateString(_dateString); trxid.appendf("%u_%s",getRandom(),_dateString.str()); }
float BeamSystem::YFunction(float beamWidth, sf::Time time) { if(time < windupTime) { return beamWidth*40*(time.asSeconds()*time.asSeconds()); } else if(time < sustainTime) { return beamWidth; } else { return beamWidth+getRandom(-sqrt(beamWidth), sqrt(beamWidth)); } }
StringBuffer& CLocalDataLogger::generateUniqueName(StringBuffer& returnName) { CriticalBlock b(crit); Owned<IJlibDateTime> _timeNow = createDateTimeNow(); SCMStringBuffer _dateString; _timeNow->getDateString(_dateString); returnName.appendf("%u_%s",getRandom(),_dateString.str()); return returnName; }
void Attack::doAction() { Damage damage = sender->getStats().damage; int realDamage = getRandom(damage.min, damage.max); realDamage = countDamageWithElement(realDamage, sender, target); target->getStats().hp.curr -= realDamage; }
void TransferServer::appendTransformed(unsigned chunkIndex, ITransformer * input) { OutputProgress & curProgress = progress.item(chunkIndex); PartitionPoint & curPartition = partition.item(chunkIndex); input->beginTransform(out); const offset_t startInputOffset = curPartition.inputOffset; const offset_t startOutputOffset = curPartition.outputOffset; loop { unsigned gotLength = input->getBlock(out); totalLengthRead += gotLength; if (gpfFrequency || !gotLength || ((unsigned)(msTick() - lastTick)) > updateFrequency) { out->flush(); lastTick = msTick(); offset_t outputOffset = out->tell(); offset_t inputOffset = input->tell(); if (totalLengthToRead) LOG(MCdebugProgress, unknownJob, "Progress: %d%% done. [%" I64F "u]", (unsigned)(totalLengthRead*100/totalLengthToRead), (unsigned __int64)totalLengthRead); curProgress.status = (gotLength == 0) ? OutputProgress::StatusCopied : OutputProgress::StatusActive; curProgress.inputLength = input->tell()-startInputOffset; curProgress.outputLength = out->tell()-startOutputOffset; if (crcOut) curProgress.outputCRC = crcOut->getCRC(); if (calcInputCRC) curProgress.hasInputCRC = input->getInputCRC(curProgress.inputCRC); sendProgress(curProgress); } if (!gotLength) break; if (blockDelay) MilliSleep(blockDelay); else if (throttleNicSpeed) { unsigned delay = (unsigned)(((unsigned __int64)gotLength*10*1000*(numParallelSlaves-1))/(throttleNicSpeed * I64C(0x100000))); if (delay) MilliSleep(delay*(getRandom()%100)/50); } #ifdef _WIN32 if (gpfFrequency && ((rand() % gpfFrequency) == 0)) { LOG(MCdebugInfo, unknownJob, "About to crash...."); *(char *)0 = 0; } #endif } input->endTransform(out); }
void pw_set(char * pw, uint16_t * k) { int i; memset(pw,0,PW_LEN); /* wipe old PW */ for(i=0;i<4;i++) k[1]=getRandom(); xxtea_encode_words(pw,PW_LEN/4,k); pw[PW_LEN]=0; }
int main() { int* vect_1 = (int*)malloc(sizeof(int) * VECTOR_SIZE); int* vect_2 = (int*)malloc(sizeof(int) * VECTOR_SIZE); int* vect_sum = (int*)malloc(sizeof(int) * VECTOR_SIZE); #pragma opm parallel for for (int i = 0; i < VECTOR_SIZE; ++i) { vect_1[i] = getRandom(0, 10); vect_2[i] = getRandom(0, 10); } #pragma omp parallel for for(int i = 0; i < VECTOR_SIZE; ++i) { vect_sum[i] = vect_1[i] + vect_2[i]; } printf("Vector 1: "); printVector(vect_1, VECTOR_SIZE); printf("\nVector 2: "); printVector(vect_2, VECTOR_SIZE); printf("\nResult Vector: "); printVector(vect_sum, VECTOR_SIZE); printf("\n"); // #pragma omp threadprivate(thread_id) // #pragma omp parallel // { // printf("%d: before!\n", thread_id); // thread_id = omp_get_thread_num(); // printf("%d: Hello world!\n", thread_id); // if(thread_id == 0) // { // num_threads = omp_get_num_threads(); // printf("Number of threads: %d\n", num_threads); // } // } return 0; }
bool CDropManager::checkProbPerLevel(const int _prob, const int _levelDiff, const int _probPerLevel) { if( _prob == 10000 ) return true; if( _prob - getProbPerLevel(_levelDiff,_probPerLevel) >= getRandom() ) return true; return false; }
MenuPrincipal::MenuPrincipal(sf::Vector2f taillePlateau, std::string theme, std::string pseudoJoueur): _focus(Focus::Jouer), _taillePlateau(taillePlateau), _fond(taillePlateau), _retournerResultat(false) { if(theme == "themePacman") _fond.setTexture(&GraphicDispatcher::getFondPacman("fond"+std::to_string(getRandom(1, 4))+".png")); else _fond.setTexture(&GraphicDispatcher::getFondLotr("fond"+std::to_string(getRandom(1, 4))+".png")); _listeEcriture.push_back(sf::Text("Menu Principal", GraphicDispatcher::getFont(0), 140)); _listeEcriture.push_back(sf::Text("Jouer", GraphicDispatcher::getFont(0), 70)); _listeEcriture.push_back(sf::Text("Options", GraphicDispatcher::getFont(0), 70)); _listeEcriture.push_back(sf::Text("Statistiques", GraphicDispatcher::getFont(0), 70)); _listeEcriture.push_back(sf::Text("Quitter", GraphicDispatcher::getFont(0), 70)); placerTexte(); }
float BeamSystem::XFunction(float beamHeight, sf::Time time) { if(time < windupTime) { return 40.0f/(time.asSeconds()*20+1); } else if(time < sustainTime) { return beamHeight*(1.0f - (sustainTime-time).asMicroseconds() /(float)(sustainTime-windupTime).asMicroseconds()); } else { return beamHeight+getRandom(-sqrt(beamHeight), sqrt(beamHeight)); } }
bool CDropManager::checkDropProb(CNPC* _pNPC, CDropInfo* _pDrop) { if( _pDrop->getProb() == -1 ) return true; if( getDropProb(_pNPC, _pDrop) >= getRandom() ) return true; return false; }
cv::Mat PCA_FilterBank(vector<cv::Mat>& InImg, int PatchSize, int NumFilters){ int channels = InImg[0].channels(); int InImg_Size = InImg.size(); int* randIdx = getRandom(InImg_Size); int size = channels * PatchSize * PatchSize; int img_depth = InImg[0].depth(); cv::Mat Rx = cv::Mat::zeros(size, size, img_depth); vector<int> blockSize; vector<int> stepSize; for(int i=0; i<2; i++){ blockSize.push_back(PatchSize); stepSize.push_back(1); } cv::Mat temp; cv::Mat mean; cv::Mat temp2; cv::Mat temp3; int coreNum = omp_get_num_procs();//»ñµÃŽŠÀíÆ÷žöÊý int cols = 0; # pragma omp parallel for default(none) num_threads(coreNum) private(temp, temp2, temp3, mean) shared(cols, Rx, InImg_Size, InImg, randIdx, blockSize, stepSize) for(int j=0; j<InImg_Size; j++){ temp = im2col_general(InImg[randIdx[j]], blockSize, stepSize); cv::reduce(temp, mean, 0, CV_REDUCE_AVG); temp3.create(0, temp.cols, temp.type()); cols = temp.cols; for(int i=0;i<temp.rows;i++){ temp2 = (temp.row(i) - mean.row(0)); temp3.push_back(temp2.row(0)); } temp = temp3 * temp3.t(); # pragma omp critical Rx = Rx + temp; } Rx = Rx / (double)(InImg_Size * cols); cv::Mat eValuesMat; cv::Mat eVectorsMat; eigen(Rx, eValuesMat, eVectorsMat); cv::Mat Filters(0, Rx.cols, Rx.depth()); for(int i=0; i<NumFilters; i++) Filters.push_back(eVectorsMat.row(i)); return Filters; }
MemoryBlock getMemoryBlockWithRandomData (size_t numBytes) { MemoryBlock block (numBytes); Random rng = getRandom(); for (size_t i = 0; i < numBytes; ++i) block[i] = (char) rng.nextInt (256); return block; }
void tick_beacon(void){ static int beaconctr=0; if(GLOBAL(privacy)>0) return; if(beaconctr--<0){ push_queue(&do_openbeacon); beaconctr=B_INTERVAL/SYSTICKSPEED/2; beaconctr+=getRandom()%(beaconctr*2); }; }
RoutePoint *EnemyData::getRoute(short routeId) { short id = getRandom(0, TerminaQuantity); //\u00BB\u00C1\u03C0\u02DA\u00AC\u2211\u00E6\u2202\u00BF\u00D4\u221A\u00CA\u00B5\u0192\u00B5\u2044\u201C\u00AA\u220F\u02C6\u0152\u00AA\u00F7\u221A\u0152\u2122-1\u0192\u00AB\u221A\u00A5\u2019\u201A\u00C3\u0131\u00AC\u2211\u00E6\u2202\u00AA\u03C0\u221A\u00AA\u201D\u2013\u00BA\u2206\u00C0\u201E\u2265\u02C6\u00BF\u00A5 if (allRoute[routeId][id].pathData.size() == 0) { countRoute(routeId, &allRoute[routeId][id].pathData); } return &allRoute[routeId][id]; }
/* * Initialize necessary variables for PSO */ void initializePSO(particle *particles, GBest& gBest, const data *datas, int data_size, int particle_size, int cluster_size) { for (int i = 0; i < particle_size; i++) { particle p; p.pBest = new data[cluster_size]; p.position = new data[cluster_size]; p.velocity = new data[cluster_size]; particles[i] = p; for (int j = 0; j < cluster_size; j++) { data d; for (int k = 0; k < DATA_DIM; k++) d.info[k] = 0; particles[i].velocity[j] = d; int rand = round(getRandom(0, data_size - 1)); particles[i].position[j] = datas[rand]; particles[i].pBest[j] = datas[rand]; } } gBest.centroids = new data[cluster_size]; for (int j = 0; j < cluster_size; j++) { data d; for (int k = 0; k < DATA_DIM; k++) d.info[k] = round(abs(getRandom(RANGE_MIN, RANGE_MAX))); gBest.centroids[j] = d; } }
matrix* getRandomMatrix(int rows, int columns){ int i, j; matrix* resultMatrix = mCreate(rows, columns); for(i = 0; i < resultMatrix->nRows; i++){ for(j = 0; j < resultMatrix->nColumns; j++){ resultMatrix->data[i][j] = getRandom(); } } return resultMatrix; }
int initGroup(int group_count, int a_min, int a_max, int b_min, int b_max) { //blk = getNewBlockInBuffer(&buf); int startnum = BLKNUM; for(int i = 0; i < group_count / group_in_blk; i++) { blk = getNewBlockInBuffer(&buf); for(int j = 0; j < group_in_blk; j++) { unsigned int a = getRandom(a_min, a_max); unsigned int b = getRandom(b_min, b_max); *(blk+j*8+0) = a; *(blk+j*8+4) = b; } if(i == (group_count / group_in_blk - 1)) *(blk+BLKSIZE-4) = (unsigned int)0; else *(blk+BLKSIZE-4) = (unsigned int)(BLKNUM+1); //printf("addr == %d\n", *(blk+BLKSIZE-4)); writeBlockToDisk(blk, BLKNUM, &buf); BLKNUM++; } return startnum; }
void generateData(Buffer* buffer) { char i = 1; printf("[%s] Starting to produce data.\n", getTime()); while(1) { bufferWrite(buffer, i); printf("[%s][%d/%d] Wrote '%d' to buffer.\n", getTime(), buffer->size, buffer->maxSize, i); i++; usleep(getRandom(SPEEDMIN, SPEEDMAX)); } }
// ============================================================================================ // randomly choose a rhythmic update rate // ============================================================================================ bool randomUpdateRate(){ bool updated = false; if(newPresence){ updateRate = (int)getRandom(FOUR_HUNDRED, EIGHT_HUNDRED); newPresence = false; } if (!presenceDetected || ignorePresence) updateRate = SMOOTH; return updated; }