// multiplication produces pairs of random numbers and // prompts user for product void multiplication() { int x; // first factor int y; // second factor int response = 0; // user response for product // use sentinel-controlled repetition cout << "Enter -1 to End." << endl; // loop until sentinel value read from user while ( response != -1 ) { x = rand() % 10; // generate 1-digit random number y = rand() % 10; // generate 1-digit random number cout << "How much is " << x << " times " << y << " (-1 to End)? "; cin >> response; // loop until sentinel value or correct response while ( (response != -1) && (response != (x * y)) ) { incorrectMessage(); cin >> response; } // end while if ( response == (x * y) ) // correct response correctMessage(); } // end while cout << "\nThat's all for now. Bye." << endl; } // end function multiplication
set<int> CMT::randomSelect(int k, int n) { if(k > n) throw Exception("k must be smaller than n."); if(k < 0 || n < 0) throw Exception("n and k must be non-negative."); // TODO: a hash map could be more efficient set<int> indices; if(k <= n / 2) { for(int i = 0; i < k; ++i) while(indices.insert(rand() % n).second != true) { // repeat until insertion successful } } else { // fill set with all indices for(int i = 0; i < n; ++i) indices.insert(i); for(int i = 0; i < n - k; ++i) while(!indices.erase(rand() % n)) { // repeat until deletion successful } } return indices; }
int main() { unsigned int array[SIZE]; unsigned int c; srand(time(nullptr)); // use current time in seconds as random seed for(c = 0 ; c < SIZE ; c++) // randomize contents of array array[c] = rand() * rand(); cout << "An array of " << SIZE << " random numbers:\n\n"; for(c = 0 ; c < SIZE ; c++) // display array (5 numbers per row) cout << setw(15) << array[c] << ((c+1)%5 ? "" : "\n"); cout << endl; bucketsort(array, SIZE); // sort array cout << "The same array sorted:\n\n"; //for( c = 0 ; c < 5 ; c++ ) // print a header? // cout << " 9876543210"; //cout << '|' << endl; for(c = 0 ; c < SIZE ; c++) // display array (5 numbers per row) cout << setw(15) << array[c] << ((c+1)%5 ? "" : "\n"); cout << endl; system("PAUSE"); return 0; } // end function main
void generate_data(mpi::communicator local, mpi::communicator world) { using std::srand; using std::rand; // The rank of the collector within the world communicator int master_collector = local.size(); srand(time(0) + world.rank()); // Send out several blocks of random data to the collectors. int num_data_blocks = rand() % 3 + 1; for (int block = 0; block < num_data_blocks; ++block) { // Generate some random data int num_samples = rand() % 1000; std::vector<int> data; for (int i = 0; i < num_samples; ++i) { data.push_back(rand()); } // Send our data to the master collector process. std::cout << "Generator #" << local.rank() << " sends some data..." << std::endl; world.send(master_collector, msg_data_packet, data); } // Wait for all of the generators to complete (local.barrier)(); // The first generator will send the message to the master collector // indicating that we're done. if (local.rank() == 0) world.send(master_collector, msg_finished); }
//------------------------------------------------------------------------------ void my1BhvScout::Evaluate(void) { mActive = true; if(mInput->info.bview) { mDrive.drive = MOVE_F; mDrive.turn = mInput->info.bside; mActive = false; // can be override } else { // basically turn away fom obstacle if(!mSense->r_safe&&mSense->l_safe) mDrive.turn = TURN_L; else if(mSense->r_safe&&!mSense->l_safe) mDrive.turn = TURN_R; else { // 1/8 chance turning mDrive.turn = rand()%2? TURN_R : TURN_L; mDrive.turn = rand()%4==0? mDrive.turn : TURN_0; } mDrive.drive = mDrive.turn? MOVE_0 : MOVE_F; // don't move if turning } // assign drive parameters mDrive.dist = mDrive.drive*1.0; mDrive.angle = mDrive.turn*0.5; // only turn half as much }
virtual void run (Arg) { ulong l1 (rand() % 1000); ulong l2 (rand() % 1000); string s1 (randStr(50)); string s2 (randStr(50)); const char* cp (s1.c_str()); verifyWrapper<ulong> (l1, l2); verifyWrapper<ulong&> (l1, l2); verifyWrapper<ulong*> (&l1, &l2); verifyWrapper<ulong*> ((0), &l2); verifyWrapper<ulong*> (&l1, (0)); verifyWrapper<ulong const&> (l1, l2); verifyWrapper<string> (s1, s2); verifyWrapper<string&> (s1, s2); verifyWrapper<string*> (&s1, &s2); verifyWrapper<const char*> (cp, "Lumiera"); verifySaneInstanceHandling(); verifySaneMoveHandling(); verifyWrappedRef (); verifyFunctionResult (); verifyFunctionRefResult (); }
// Generates a random position in the rectangle created by MinPos and MaxPos POS_2D GetRandomPosition(POS_2D MinPos, POS_2D MaxPos) { POS_2D newPos; newPos.X = rand()%(MaxPos.X-MinPos.X+1) + MinPos.X; newPos.Y = rand()%(MaxPos.Y-MinPos.Y+1) + MinPos.Y; return newPos; }
/*The populate matricies function is to define the variables mA and mB and to set it up. The conditional statements in lines 17 through 20 set up the size of the rows and columns lines 22 and 23 define the numbers that will be in the matricies. to be random numbers that must be between 0 and nine. */ void populateMatrices(vector<int>& mA, vector<int>& mB, int ROWS, int COLUMNS) { for (int rowIdx = 0; rowIdx < ROWS; rowIdx++) { for (int columnIdx = 0; columnIdx < COLUMNS; columnIdx++) { mA[rowIdx + columnIdx] = rand() % 10; mB[rowIdx + columnIdx] = rand() % 10; } } }
//起始乱序分牌 void GameServer::mixedOrder(int x[], int n) { srand(static_cast<unsigned int>(time(0))); int index1,index2,tmp; for(int i=0;i<n;i++){ index1=rand()%54; index2=rand()%54; tmp=x[index1]; x[index1]=x[index2]; x[index2]=tmp; } }
int rollDice() { int die1 = 1 + rand() % 6; int die2 = 1 + rand() % 6; int sum = die1 + die2; cout << "Player rolled " << die1 << " + " << die2 << " = " << sum << endl; return sum; }
void ScenePointSprite::initScene() { compileAndLinkShader(); glClearColor(0.5f,0.5f,0.5f,1.0f); glEnable(GL_DEPTH_TEST); //float c = 2.5f; //projection = glm::ortho(-0.4f * c, 0.4f * c, -0.3f *c, 0.3f*c, 0.1f, 100.0f); angle = (float)(PI / 2.0); numSprites = 50; locations = new float[numSprites * 3]; srand( (unsigned int)time(0) ); for( int i = 0; i < numSprites; i++ ) { vec3 p(((float)rand() / RAND_MAX * 2.0f) - 1.0f, ((float)rand() / RAND_MAX * 2.0f) - 1.0f, ((float)rand() / RAND_MAX * 2.0f) - 1.0f); locations[i*3] = p.x; locations[i*3+1] = p.y; locations[i*3+2] = p.z; } // Set up the buffers GLuint handle; glGenBuffers(1, &handle); glBindBuffer(GL_ARRAY_BUFFER, handle); glBufferData(GL_ARRAY_BUFFER, numSprites * 3 * sizeof(float), locations, GL_STATIC_DRAW); delete [] locations; // Set up the vertex array object glGenVertexArrays( 1, &sprites ); glBindVertexArray(sprites); glBindBuffer(GL_ARRAY_BUFFER, handle); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, ((GLubyte *)NULL + (0)) ); glEnableVertexAttribArray(0); // Vertex position glBindVertexArray(0); // Load texture file glActiveTexture(GL_TEXTURE0); GLuint tid = SOIL_load_OGL_texture("flower.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS|SOIL_FLAG_INVERT_Y); glBindTexture(GL_TEXTURE_2D, tid); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); prog.setUniform("SpriteTex", 0); prog.setUniform("Size2", 0.15f); }
int *line_segments_generation() { int *lines = new int[LINE_NUM*4]; srand(time(0)); for (int i = 0; i < LINE_NUM; i++) { lines[4*i] = rand() % W; lines[4*i + 1] = rand() % H; lines[4*i + 2] = rand() % W; lines[4*i + 3] = rand() % H; } return lines; }
int main () { srand ( time ( 0 ) ); int a; string c; int levelup = 1; int rCount = 0; int level; cout << "Enter your level ( 1 for one-bit, 2 for two-bit and so on ): "; cin >> level; for ( int count = 1; count <= level; count++ ) levelup *= 10; levelup--; for ( int count = 1; count <= 10; count++ ) { int x = 1 + rand() % 9, y = 1 + rand() % levelup; cout << "What is " << x << " multiple by " << y << "?" << endl; int z; cin >> z; a = 1 + rand() % 4; switch ( a ) { case 1: c = "Very well"; break; case 2: c = "Perfectly!"; break; case 3: c = "Great job!"; break; case 4: c = "Keep working in the same spirit!"; break; } if ( z == x * y ) { cout << c << endl; rCount++; } else repeat( x, y, z ); } if ( ( rCount * 10 ) < 75 ) cout << "Please ask your teacher to help you!" << endl; return 0; }
int main() { int n = 1000; int capacity = 2000000; vector<int> weights (n); vector<int> values (n); for (int i=0;i<n;i++) { weights[i] = rand()%capacity; values[i] = rand()%capacity; } double optimal_value = get_optimal_value(capacity, weights, values); std::cout.precision(10); std::cout << optimal_value << std::endl; return 0; }
// generate number from 1 to factor-1 inline int generateNumber( int factor=1 ) { int power; power = pow( 10, factor); // generate number from 1 to power-1 e.g. 1 to 9; 1 to 99 return (1 + rand() % (power-1)); }
/* Purpose: To shuffle the cards in the Deck, can be more than once but will be Less than or equal to the MAX_SHUFFLE count, prevents from shuffling the Deck 4 billion times. Entry: The number of times to shuffle the Deck Exit: The cards in the deck have now been placed in a random order */ void Deck::Shuffle(int TimesToShuffle) { cout << "Will shuffle " << TimesToShuffle << " times." << endl; if((TimesToShuffle > 0) && (TimesToShuffle <= MAX_SHUFFLE)) { int iCount = 0; while(iCount < TimesToShuffle) { for(int i = 0; i < MAX_NUMBER_OF_CARDS; i++) { srand(static_cast<int>(time(0))); int RandomNumber = rand() % MAX_NUMBER_OF_CARDS; Card Temp = m_Deck[i]; m_Deck[i] = m_Deck[RandomNumber]; m_Deck[RandomNumber] = Temp; } iCount++; } } else { cout << "The number of times to shuffle is not a valid value!" << endl; } }
void verify_MultimapIters() ///< @see IterTools_test#verify_filterRepetitions { MAP testMap; for (uint i=0; i<NUM_ELMS; ++i) { uint n = 1 + rand() % 100; do testMap.insert (make_pair (i,n)); while (--n); } CHECK (NUM_ELMS < testMap.size(), "no repetition in test data??"); IntIter keys = eachDistinctKey (testMap); cout << "distinct_keys"; CHECK (keys); pullOut (keys); CHECK (!keys); cout << "values_4_key"; IntIter vals = eachValForKey (testMap, NUM_ELMS); // non-existent key CHECK (!vals); vals = eachValForKey (testMap, 0); CHECK (vals); pullOut (vals); // should produce anything between 1 and 100 entries CHECK (!vals); }
// 洗牌和发牌 void DeckOfCards::shuffleAndDeal() { int row; int column; for (int card = 1; card <= 52; card++) { do { row = rand() % 4; // 随机花色 column = rand() % 13; // 随机数字 } while (deck[row][column] != 0); deck[row][column] = card; cout << showCard(row, column) << (card % 2 == 0 ? '\n' : '\t'); } }
// Display message for correct answer // To reduce student fatigue, display four different messages based on generated // random number void displayAfterCorrectAnswer() { srand( time(NULL) ); int numberMessage; numberMessage = (rand() % 4 + 1); // random generate number from 1 to 4 // Display different messages based on random number generated switch( numberMessage ) { case 1: cout << "Very good!" << endl; break; case 2: cout << "Excellent!" << endl; break; case 3: cout << "Nice work!" << endl; break; case 4: cout << "Keep up the good work!" << endl; break; default: cout << "Uknown case..." << endl; break; } }
MatrixXd CMT::MLR::sample(const MatrixXd& input) const { if(input.rows() != mDimIn) throw Exception("Inputs have wrong dimensionality."); // distribution over outputs ArrayXXd prob = predict(input); MatrixXd output = MatrixXd::Zero(mDimOut, input.cols()); #pragma omp parallel for for(int j = 0; j < input.cols(); ++j) { double urand = static_cast<double>(rand()) / RAND_MAX; double cdf = 0.; for(int k = 0; k < mDimOut; ++k) { cdf += prob(k, j); if(urand < cdf) { output(k, j) = 1.; break; } } } return output; }
// guessGame generates numbers between 1 and 1000 and checks user's guess void guessGame() { int answer; // randomly generated number int guess; // user's guess char response; // 'y' or 'n' response to continue game // loop until user types 'n' to quit game do { // generate random number between 1 and 1000 // 1 is shift, 1000 is scaling factor answer = 1 + rand() % 1000; // prompt for guess cout << "I have a number between 1 and 1000.\n" << "Can you guess my number?\n" << "Please type your first guess." << endl << "? "; cin >> guess; // loop until correct number while ( !isCorrect( guess, answer ) ) cin >> guess; // prompt for another game cout << "\nExcellent! You guessed the number!\n" << "Would you like to play again (y or n)? "; cin >> response; cout << endl; } while ( response == 'y' ); } // end function guessGame
// Display message for wrong answer void displayAfterWrongAnswer() { srand( time(NULL) ); // seed random generator int numberMessage; // random number to display different messages numberMessage = (rand() % 4 + 1); // random number from 1 to 4 // Display different messages based on random number generated switch( numberMessage ) { case 1: cout << "No. Please try again." << endl; break; case 2: cout << "Wrong. Try once more." << endl; break; case 3: cout << "Don't give up!" << endl; break; case 4: cout << "Keep trying." << endl; break; default: cout << "Uknown case..." << endl; break; } }
double PleC::uniRandNum(){ double r1; do{r1=1.0*rand()/RAND_MAX;}while(r1<=0 || r1>=1); return r1; }
string generatePhrase(string a1[20], string a2[20], string a3[20] ) { std::stringstream ss; char s[256]; int i1, i2, i3; i1 = rand() % 6; i2 = rand() % 5; i3 = rand() % 7; ss << a1[i1] SPC a2[i2] SPC a3[i3]; ss.getline(s, 256); return s; }
void ScenePointSprite::initScene() { compileAndLinkShader(); glClearColor(0.5f,0.5f,0.5f,1.0f); glEnable(GL_DEPTH_TEST); numSprites = 50; locations = new float[numSprites * 3]; srand( (unsigned int)time(0) ); for( int i = 0; i < numSprites; i++ ) { vec3 p(((float)rand() / RAND_MAX * 2.0f) - 1.0f, ((float)rand() / RAND_MAX * 2.0f) - 1.0f, ((float)rand() / RAND_MAX * 2.0f) - 1.0f); locations[i*3] = p.x; locations[i*3+1] = p.y; locations[i*3+2] = p.z; } // Set up the buffers GLuint handle; glGenBuffers(1, &handle); glBindBuffer(GL_ARRAY_BUFFER, handle); glBufferData(GL_ARRAY_BUFFER, numSprites * 3 * sizeof(float), locations, GL_STATIC_DRAW); delete [] locations; // Set up the vertex array object glGenVertexArrays( 1, &sprites ); glBindVertexArray(sprites); glBindBuffer(GL_ARRAY_BUFFER, handle); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, ((GLubyte *)NULL + (0)) ); glEnableVertexAttribArray(0); // Vertex position glBindVertexArray(0); // Load texture file GLuint w, h; const char * texName = "../media/texture/flower.bmp"; BMPReader::loadTex(texName, w, h); prog.setUniform("SpriteTex", 0); prog.setUniform("Size2", 0.15f); }
void init(list<int>& list) { while (list.size() < 10000) { int add = rand() % 20000; list.push_back(add); list.sort(); list.unique(); } }
double unit_uniform_random_variable() { double x; do { x = double(rand())/RAND_MAX; } while (x == 0.0 || x == 1.0); return x; }
void my_qsort(int * arr, int n) { if (n <= 1) return; // массив в 1 или 0 элементов уже упорядочен int * pivotPtr = arr + rand() % n; // случайный выбор опорного элемента int newPivotIdx = partition(arr, arr + n - 1, pivotPtr) - arr; my_qsort(arr, newPivotIdx); my_qsort(arr + newPivotIdx + 1, n - (newPivotIdx + 1)); }
void repeat ( int x, int y, int z ) { int a, b; string c, d; a = 1 + rand() % 4, b = 1 + rand() % 4; switch ( a ) { case 1: c = "Very well"; break; case 2: c = "Perfectly!"; break; case 3: c = "Great job!"; break; case 4: c = "Keep working in the same spirit!"; break; } switch ( b ) { case 1: d = "It's wrong! Try again!"; break; case 2: d = "No. Please try again!"; break; case 3: d = "Do not be discouraged!"; break; case 4: d = "No. Continue your attempts!"; break; } if ( z == x * y ) cout << c << endl; else { cout << d << endl; cout << "What is " << x << " multiple by " << y << "?" << endl; cin >> z; repeat ( x, y, z ); } }
void my_qsort(int * arr, int l, int r) { if (l >= r) return; int pivot = rand() % (r - l) + l; int j = partition(arr, l, r, pivot); my_qsort(arr, l, j); my_qsort(arr, j + 1, r); }