/* Generates and return a vector of food elements. Limited to one food elements, but can be list can be filled width more elements if needed */ vector<Cell>& FoodProvider::provideFood(Snake snake, int windowWidth, int menuBorderHeight) { bool okCoords; int randomWidth = -1; int randomHeight = -1; /* Makes sure a food element is not writting on top of a snake cell */ do { okCoords = true; for(int i = 0; i < snake.getCells().size(); i++) { Cell currCell = snake.getCells().at(i); //Generates a random x coordionate randomWidth = generateRandomNumber(windowWidth); //Generates a random y coordinate randomHeight = generateRandomNumber(menuBorderHeight); if(currCell.getX() == randomWidth && currCell.getY() == randomHeight) { okCoords = false; break; } } }while(!okCoords); //Adds a food elements foodList.push_back(Cell(randomWidth, randomHeight, '$')); return foodList; }
// move the gun base on the scan //if not move to the side which has more space void FoeReaper4000RobotCpp::optimizeGunPosition() { //TODO: check if scanner find the enemy if (keepStay) { shootToPos(lastEnemyPos); return; } RWVec robotPos = position(); RWSize areaSize = arenaDimensions(); float x,y; if (robotPos.x > (areaSize.width - robotPos.x)) { x = generateRandomNumber(0.0f, robotPos.x); } else { x = generateRandomNumber(robotPos.x, areaSize.width); } if (robotPos.y > (areaSize.height - robotPos.y)) { y = generateRandomNumber(0.0f, robotPos.y); } else { y = generateRandomNumber(robotPos.y, areaSize.height); } shootToPos(RWVec(x, y)); }
//int beginDegree = 0, int endDegree = 360, int beginDistance = 50, int EndDistance = 100 void FoeReaper4000RobotCpp::randomWalk(int beginDegree, int endDegree, int beginDistance, int endDistance) { int nextDistance = generateRandomNumber(beginDistance, endDistance); int nextDegree = generateRandomNumber(beginDegree, endDegree); if (! keepStay) { optimizeMove(nextDegree,nextDistance); } optimizeGunPosition(); }
//----------------------------------------------------------------------------- // GLOBAL operation generateInitialGraph(int sourceGraphOrder) // RETURNS a random graph with sourceGraphOrder vertex //----------------------------------------------------------------------------- void StrategyPatternAlgorithm::generateInitialGraph(int sourceGraphOrder){ int i,j; int newNeighbour; int newDegree; CFuncTrace trace (false,"StrategyPatternAlgorithm::generateInitialGraph"); this->sourceGraph=new gslGraph(sourceGraphOrder); for(i=0; i<sourceGraphOrder; i++){ trace.trace(STP_DEBUG,"Iteration %d",i); trace.trace(STP_DEBUG,"Iteration %d sourceGraphOrder %d Degree %d", i,sourceGraphOrder,this->sourceGraph->getDegree(i)); // The new vertex degree is to be // at least 1 (the graphs needs to be connected) // at most n-1 (the vertex is connected to every other vertex if(this->sourceGraph->getDegree(i)==0){ // vertex i has no neighbours yet // settingsSimulation->random_value_z = settingsSimulation->random_value_z-> newDegree=1+(int)(generateRandomNumber()*(sourceGraphOrder-1)); // newDegre is in [1,n-1] } else if(this->sourceGraph->getDegree(i)<(sourceGraphOrder-1)){ // vertex i is connected to some other vertex newDegree=(int)(generateRandomNumber()* (sourceGraphOrder-this->sourceGraph->getDegree(i))); // newDegree is in [0,n-1-degree] } else { // vertex i is already connected to all possible neighbours newDegree=0; } trace.trace(STP_DEBUG,"Iteration %d NewDegree for node %i is %d", i,i,newDegree); int vertexAreNighbours = 0; for(j=0;j<newDegree;j++){ do{ newNeighbour=(int)(generateRandomNumber()*(sourceGraphOrder)); // newNeighbour is in [0,n-1] trace.trace(STP_DEBUG,"Is Neighbour %d to %d", newNeighbour,i); vertexAreNighbours = this->sourceGraph->vertexAreNeighbours(i,newNeighbour); if (vertexAreNighbours) trace.trace(STP_DEBUG,"ATT : VERTEX Are Nighbours"); // Added linia 2014-11-27 //vertexAreNighbours = ( i == newNeighbour); } while(vertexAreNighbours); trace.trace(STP_DEBUG,"Adding newNeighbour %d to %d", i, newNeighbour); this->sourceGraph->addVertexNeighbour(i,newNeighbour); } } }
void FoeReaper4000RobotCpp::hitWallWithSideAndAngle(RobotWallHitSide::RobotWallHitSide side, float hitAngle) { this->cancelActiveAction(); RWSize areaSize = arenaDimensions(); switch (side) { case RobotWallHitSide::FRONT: { float x = generateRandomNumber(areaSize.width/4,areaSize.width/4*3); float y = 0.0f; int angle = (int) angleBetweenHeadingDirectionAndWorldPosition(RWVec(x, y)); randomWalk(angle,angle,150,200); } break; case RobotWallHitSide::REAR: { float x = generateRandomNumber(areaSize.width/4,areaSize.width/4*3); float y = areaSize.height; int angle = (int) angleBetweenHeadingDirectionAndWorldPosition(RWVec(x, y)); randomWalk(angle,angle,150,200); } break; case RobotWallHitSide::LEFT: { float x = 0.0; float y = generateRandomNumber(areaSize.height/4, areaSize.height/4*3); int angle = (int) angleBetweenHeadingDirectionAndWorldPosition(RWVec(x, y)); randomWalk(angle,angle,150,200); } break; case RobotWallHitSide::RIGHT: { float x = areaSize.width; float y = generateRandomNumber(areaSize.height/4, areaSize.height/4*3); int angle = (int) angleBetweenHeadingDirectionAndWorldPosition(RWVec(x, y)); randomWalk(angle,angle,150,200); } break; case RobotWallHitSide::NONE: break; } }
/* In the init method, initializes the particles at the center of the window. In the terms of the element, the element will move between -1 to 1 on the window as x and y are further multiplied by window width and height to get the actual position. The element position and color functionality is implemented in the Window::setColors */ void Element::init() { //Initialize the particle to the center of the window postionX = 0; positionY = 0; /* During an explosion the elements move from center of explosion in a spherical path 360 degrees in all directions. In terms of radians a 360 degrees is represented by 2*PI. By multiplying the 360 degrees or here 2*PI with a double between 0 and 1 will give a random angle between 0 and 360 degrees or here 0 and 2*PI */ elementMotionDirection = 2*M_PI*generateRandomNumber(0, 1); elementSpeed = elementSpeedConstant*generateRandomNumber(0,1); //This makes the particles travel faster as they approach the edges of the screen giving an uneven distribution across the window elementSpeed *= elementSpeed; }
AMNumber AMMockDetector::reading(const AMnDIndex &indexes) const { // We want an "invalid" AMnDIndex for this 0D detector if (indexes.isValid()) { return AMNumber(AMNumber::DimensionError); } return generateRandomNumber(); }
/** * Create Diffie-Hellman parameters and save them to files. * Compute the shared secret and computed key from the received other public key. * Save shared secret and computed key to file. */ bool replyToFirstMessage() { cout << "Reply To First Message" << endl; // Split received file into separate files vector<string> outputFiles; outputFiles.push_back(OTHER_FIRST_MESSAGE_RANDOM_NUMBER); outputFiles.push_back(OTHER_PUBLIC_KEY_FILE_NAME); vector<int> bytesPerFile; bytesPerFile.push_back(RANDOM_NUMBER_SIZE); splitFile(FIRST_MESSAGE_FILE_NAME, outputFiles, bytesPerFile); // Read in received Diffie-Hellman public key from file SecByteBlock otherPublicKey; readFromFile(OTHER_PUBLIC_KEY_FILE_NAME, otherPublicKey); // Read in received random number from file SecByteBlock otherFirstMessageRandomNumber; readFromFile(OTHER_FIRST_MESSAGE_RANDOM_NUMBER, otherFirstMessageRandomNumber); // Prepare Diffie-Hellman parameters SecByteBlock publicKey; SecByteBlock privateKey; generateDiffieHellmanParameters(publicKey, privateKey); // Write public key and private key to files writeToFile(PRIVATE_KEY_FILE_NAME, privateKey); writeToFile(PUBLIC_KEY_FILE_NAME, publicKey); // Compute shared secret SecByteBlock sharedSecret; if (!diffieHellmanSharedSecretAgreement(sharedSecret, otherPublicKey, privateKey)) { cerr << "Security Error in replyToFirstMessage. Diffie-Hellman shared secret could not be agreed to." << endl; return false; } // Compute key from shared secret SecByteBlock key; generateSymmetricKeyFromSharedSecret(key, sharedSecret); // Write shared secret and computed key to file writeToFile(SHARED_SECRET_FILE_NAME, sharedSecret); writeToFile(COMPUTED_KEY_FILE_NAME, key); // Generate random number SecByteBlock firstMessageRandomNumber; generateRandomNumber(firstMessageRandomNumber, RANDOM_NUMBER_SIZE); // Write random number to file writeToFile(FIRST_MESSAGE_RANDOM_NUMBER_FILE_NAME, firstMessageRandomNumber); vector<string> inputFileNames; inputFileNames.push_back(FIRST_MESSAGE_RANDOM_NUMBER_FILE_NAME); inputFileNames.push_back(PUBLIC_KEY_FILE_NAME); combineFiles(inputFileNames, FIRST_MESSAGE_REPLY_FILE_NAME); return true; }
void OmplRosRPYIKStateTransformer::generateRandomState(arm_navigation_msgs::RobotState &robot_state) { std::vector<const planning_models::KinematicModel::JointModel*> joint_models = physical_joint_model_group_->getJointModels(); for(unsigned int i=0; i < robot_state.joint_state.name.size(); i++) { std::pair<double,double> bounds; joint_models[i]->getVariableBounds(robot_state.joint_state.name[i],bounds); robot_state.joint_state.position[i] = generateRandomNumber(bounds.first,bounds.second); } }
bool AMMockDetector::data(double *outputValues) const { if(!outputValues) { return false; } outputValues[0] = generateRandomNumber(); return true; }
//----------------------------------------------------------------------------- // GLOBAL operation modifyGraph(sourceGraph) // MODIFIES a randon sourceGraph vertex's connections //----------------------------------------------------------------------------- void StrategyPatternAlgorithm::modifyGraph(gslGraph *sourceGraph, int LevelGraph){ int i,j; int vertex2change; int myOrder=sourceGraph->getOrder(); int myNewNeighbour; int myNewNumberOfNeighbours; int newNeighbours[myOrder]; int found; // CFuncTrace lFuncTrace(false,"StrategyPatternAlgorithm::modifyGraph"); // Select vertex to change vertex2change=(int)(generateRandomNumber()*(myOrder)); sourceGraph->removeVertexNeighbours(vertex2change); // sourceGraph->printGraph(LevelGraph); // lFuncTrace.trace(LevelGraph,"modifyGraph vertex removed %d\n",vertex2change); do{ //Choose new vertex degree myNewNumberOfNeighbours=1+(int)(generateRandomNumber()*(myOrder-1)); // lFuncTrace.trace(LevelGraph,"New Degree %d for vertex %d\n",myNewNumberOfNeighbours,vertex2change); // myNewNumberOfNeighbours is in [1,n-1] // Connect new neighbours for(i=0; i<myNewNumberOfNeighbours; i++){ do{ found=false; myNewNeighbour=(int)(generateRandomNumber()*(myOrder)); // myNewNeighbour is in [0,n-1] for(j=0;j<i;j++){ if((myNewNeighbour==newNeighbours[j]) ||(myNewNeighbour==vertex2change)){ found=true; } } } while(found|| (sourceGraph->vertexAreNeighbours(vertex2change,myNewNeighbour))); newNeighbours[i]=myNewNeighbour; sourceGraph->addNewVertexNeighbour(vertex2change,myNewNeighbour); } } while (sourceGraph->graphNotConnected(&vertex2change)); }
/*! \internal */ QByteArray WebSocket::generateKey() const { QByteArray key; for (int i = 0; i < 4; ++i) { quint32 tmp = generateRandomNumber(); key.append(static_cast<const char *>(static_cast<const void *>(&tmp)), sizeof(quint32)); } return key.toBase64(); }
Particle ParticleSystem::generateNewParticle(){ Particle newPart; newPart.azimuthRoation = generateRandomNumber(MIN_ROTATION, MAX_ROTATION); newPart.zenithRotation = generateRandomNumber(MIN_ROTATION, MAX_ROTATION); newPart.surfaceTranslationFactor = generateRandomNumber(MIN_TRANS, MAX_TRANS); newPart.deltaAz = generateRandomNumber(MIN_DELTA_ROTATION, MAX_DELTA_ROTATION); newPart.deltaZe = generateRandomNumber(MIN_DELTA_ROTATION, MAX_DELTA_ROTATION); newPart.deltaSurface = generateRandomNumber(MIN_DELTA_SURFACE, MAX_DELTA_SURFACE); newPart.lifetime = (int)generateRandomNumber(MIN_LIFETIME, MAX_LIFETIME); return newPart; }
// MT // Generate priority for PCB's int generatePriority() { int n = generateRandomNumber(1, 100); int priority; switch(n) { case 6 < n: priority = 0; break; case 11 < n: priority = 3; break; case 21 < n: priority = 2; break; default: priority = 1; break; } return priority; }
char *getRandomSS() { FILE *ifp; ifp = fopen("chainlist.txt", "r"); char *contentsOfLine = calloc(100, sizeof(char)); int numberOfLinesInFile = 0; int lineCounter = 1; char ch; int positionOfCharInLine = 0; int randomNumber = 0; /*Get the characters on the first line of the file which will be the number of lines in the file*/ while ((ch = fgetc(ifp)) != '\n') { if (ch != '\n') { contentsOfLine[positionOfCharInLine] = ch; } else { break; } positionOfCharInLine++; } numberOfLinesInFile = atoi(contentsOfLine); randomNumber = (generateRandomNumber(numberOfLinesInFile)) + 1; char *line = calloc(30, sizeof(char)); while (fgets(line, 30, ifp)) { if (lineCounter == randomNumber) { fclose(ifp); return line; } lineCounter++; memset(line, 0, 30); } }
/** * Create Diffie-Hellman parameters and save them to files. */ void firstMessage() { cout << "First Message" << endl; // Prepare Diffie-Hellman parameters SecByteBlock publicKey; SecByteBlock privateKey; generateDiffieHellmanParameters(publicKey, privateKey); // Write public key and private key to files writeToFile(PRIVATE_KEY_FILE_NAME, privateKey); writeToFile(PUBLIC_KEY_FILE_NAME, publicKey); // Generate random number SecByteBlock firstMessageRandomNumber; generateRandomNumber(firstMessageRandomNumber, RANDOM_NUMBER_SIZE); // Write random number to file writeToFile(FIRST_MESSAGE_RANDOM_NUMBER_FILE_NAME, firstMessageRandomNumber); // Combine public key and random number into one file vector<string> inputFiles; inputFiles.push_back(FIRST_MESSAGE_RANDOM_NUMBER_FILE_NAME); inputFiles.push_back(PUBLIC_KEY_FILE_NAME); combineFiles(inputFiles, FIRST_MESSAGE_FILE_NAME); }
void generatePuzzle() { printf("Generating Puzzle:\n"); size_t keyCount = 0; size_t targetCount = 0; int i = 0; // Get current image count in database redisReply *getReply = redisCommand(Context, "SCARD %s", GRP_TARGET_NAME); keyCount = getReply->integer; freeReplyObject(getReply); // Check if there is right amount of images if (keyCount >= MIN_IMAGE_TYPES) { /* * Get background */ // Get background size redisReply *backgroundSize = redisCommand(Context, "SCARD %s", GRP_BACKGROUND_NAME); char backgroundNumber[4]; char backgroundFileName[64]; int randomBackgroundNumber = 1; targetCount = backgroundSize->integer; if (randomBackgroundNumber != (int)targetCount) { randomBackgroundNumber = generateRandomNumber(1, (int)backgroundSize->integer); } snprintf(backgroundNumber, 4, "%d", randomBackgroundNumber); strcpy(backgroundFileName, ""); strcat(backgroundFileName, BackgroundDIR); strcat(backgroundFileName, "/"); strcat(backgroundFileName, BackgroundDIR); strcat(backgroundFileName, backgroundNumber); strcat(backgroundFileName, ".jpg"); printf("\nPicked %s%s as background\n", BackgroundDIR, backgroundNumber); freeReplyObject(backgroundSize); // Get a background image gdImagePtr background = loadImage(backgroundFileName, ".jpg"); if (background == NULL) { // Exit out printf("Error opening background image\n"); return; } int randomArray[MIN_IMAGE_TYPES] = {0, 0, 0, 0, 0}; generateRandomTargetGroups(1, MIN_IMAGE_TYPES, randomArray); redisReply *targetList = redisCommand(Context, "SMEMBERS %s", GRP_TARGET_NAME); printf("\nPicked targets Below:\n"); for (i = 0; i < MIN_IMAGE_TYPES; i++) { // Check if there is min amount of images redisReply *minImages = redisCommand(Context, "SCARD %s", targetList->element[i]->str); if (minImages->integer >= MIN_EACH_TYPE) { redisReply *currentTarget = redisCommand(Context, "SMEMBERS %s", targetList->element[i]->str); int randomTargetArray[MIN_EACH_TYPE] = {0, 0, 0}; generateRandomTargetGroups(1, MIN_EACH_TYPE, randomTargetArray); printf("\nFor %s we are using:\n", targetList->element[i]->str); int j = 0; for (j = 0; j < MIN_EACH_TYPE; j++) { /* * Get Each Target */ char targetFileName[64]; strcpy(targetFileName, ""); strcat(targetFileName, TargetDIR); strcat(targetFileName, "/"); strcat(targetFileName, currentTarget->element[j]->str); strcat(targetFileName, ".png"); printf("\t%s\n", currentTarget->element[j]->str); // Get a background image gdImagePtr targetImage = loadImage(targetFileName, ".png"); int top = generateRandomNumber(100, (background->sx - 100)); int bottom = top + targetImage->sy; int left = generateRandomNumber(100, (background->sy - 100)); int right = left + targetImage->sx; // Write out info to file FILE *coords = fopen("puzzle.txt", "a"); fprintf(coords, "%d, %d, %d, %d\n", top, bottom, left, right); fclose(coords); gdImageCopy(background, targetImage, top, left, 0, 0, 100, targetImage->sy); gdImageDestroy(targetImage); } // Free freeReplyObject(currentTarget); } else { printf("Add %lld more target groups to %s\n", (MIN_EACH_TYPE - minImages->integer), targetList->element[0]->str); break; } // Get random image category for user to chose redisReply *targetListCount = redisCommand(Context, "SCARD %s", GRP_TARGET_NAME); int randomTargetGroup = generateRandomNumber(1, (int)targetListCount->integer); freeReplyObject(targetListCount); redisReply *currentTarget = redisCommand(Context, "SMEMBERS %s", targetList->element[randomTargetGroup-1]->str); char *fileName = currentTarget->element[0]->str; char fileNameFinal[64]; strcpy(fileNameFinal, ""); strcat(fileNameFinal, TargetDIR); strcat(fileNameFinal, "/"); strcat(fileNameFinal, fileName); strcat(fileNameFinal, ".png"); // Get image of random target gdImagePtr lookingFor = loadImage(fileNameFinal, ".png"); // Make HTML page generateHTML(background, lookingFor); freeReplyObject(currentTarget); freeReplyObject(minImages); } gdImageDestroy(background); freeReplyObject(targetList); } else { printf("Add %lu more target groups\n", (MIN_IMAGE_TYPES - keyCount)); } }
/*! \internal */ quint32 WebSocket::generateMaskingKey() const { return generateRandomNumber(); }
AMNumber AMMockDetector::singleReading() const { return generateRandomNumber(); }
void *work(void *arg_struct) { struct q_args *args = arg_struct; long *tid = args->tid; const gsl_rng_type *T; gsl_rng *r; T = gsl_rng_taus; r = gsl_rng_alloc (T); gsl_rng_set(r, *tid); if (*tid != 0) { return NULL; } struct timespec *tp_rt_start = (struct timespec*) malloc (sizeof (struct timespec)); struct timespec *tp_rt_end = (struct timespec*) malloc (sizeof (struct timespec)); struct timespec *result = (struct timespec*) malloc (sizeof (struct timespec)); clock_gettime(CLOCK_REALTIME, tp_rt_start); struct stat st = {0}; if (stat("/tmp/distributed_queue", &st) == -1) { mkdir("/tmp/distributed_queue", 0777); } long qid = 0; unsigned int lowRange = 1; int *rn; int x = 0; if ( item_amount > 0 ) { clock_gettime(CLOCK_REALTIME, tp_rt_start); while(1) { rn = generateRandomNumber(lowRange, 100, r); if (rn == NULL) continue; dq_insert_item_by_tid(&qid, rn); free(rn); n_inserted++; int *retval = (int*) malloc(sizeof(int)); dq_remove_item_by_tid(&qid, retval); n_removed++; for (int i = 0; i < *retval; i++) { *retval = log2(*retval); } //sum += *retval; free(retval); x++; if (x == 5000) { x = 0; if ( n_removed >= item_amount ) { clock_gettime(CLOCK_REALTIME, tp_rt_end); time_diff(tp_rt_start, tp_rt_end, result); printf("Final realtime program time = %ld sec and %ld nsec\n", result->tv_sec, result->tv_nsec); printf("Total Inserted %lu items\n", n_inserted); printf("Total removed items %lu items\n", n_removed); printf("Sum of items is %lu\n", sum); gsl_rng_free(r); free(result); free(tp_rt_start); free(tp_rt_end); return NULL; } } } } else if ( program_duration > 0 ) { clock_gettime(CLOCK_REALTIME, tp_rt_start); while(1) { rn = generateRandomNumber(lowRange, 100, r); if (rn == NULL) continue; dq_insert_item_by_tid(&qid, rn); free(rn); n_inserted++; int *retval = (int*) malloc(sizeof(int)); dq_remove_item_by_tid(&qid, retval); n_removed++; for (int i = 0; i < *retval; i++) { *retval = log2(*retval); } //sum += *retval; free(retval); x++; if (x == 5000) { x = 0; clock_gettime(CLOCK_REALTIME, tp_rt_end); time_diff(tp_rt_start, tp_rt_end, result); if ( result->tv_sec >= program_duration ) { printf("Final realtime program time = %ld sec and %ld nsec\n", result->tv_sec, result->tv_nsec); printf("Total Inserted %lu items\n", n_inserted); printf("Total removed items %lu items\n", n_removed); printf("Sum of items is %lu\n", sum); gsl_rng_free(r); free(result); free(tp_rt_start); free(tp_rt_end); return NULL; } } } } return NULL; }