/* 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; } }
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
// 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; } }
int main() { typedef pair<string, string> ps; ifstream i("d.txt"); vector<ps> dict; string str1, str2; // read wirds from dictionary while (i >> str1 >> str2) { dict.emplace_back(str1, str2); } i.close(); // sort words in vector sort(dict.begin(), dict.end(), [](const ps &_ps1, const ps &_ps2){ return _ps1.first < _ps2.first; }); i.open("i.txt"); default_random_engine e(time(0)); // read words from text while (i >> str1) { // find word in dictionary vector<ps>::const_iterator it = find_if(dict.cbegin(), dict.cend(), [&str1](const ps &_ps){ return _ps.first == str1; }); // if word doesn't exist in dictionary if (it == dict.cend()) { // write it itself cout << str1 << ' '; } else { // get random meaning of word uniform_int_distribution<unsigned> u (0, find_if(dict.cbegin(), dict.cend(), [&str1](const ps &_ps){ return _ps.first > str1; }) - it - 1); // write random meaning cout << (it + u(e))->second << ' '; } } return 0; }
// 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; } }
int main() { srand( time(NULL) ); //seed random generator while( 1 ) { int number1 = generateNumber(); // generate one number int number2 = generateNumber(); // generate second number int correctResult = -1; correctResult = number1 * number2; // correct multiplication result // display which numbers are being multiplyed // To exit loop, input 0 displayMessage( number1, number2 ); int userResult = -1; // user result of multiplication cin >> userResult; // read input // exit program if( userResult == 0 ) break; // repeat until result is correct while( userResult != correctResult ) { displayAfterWrongAnswer(); cin >> userResult; } // display message for correct result if( userResult == correctResult ) displayAfterCorrectAnswer(); } return 0; }// end main function
int main() { srand( time( 0 ) ); // seed random number generator multiplication(); // begin multiplication practice system("pause"); // enter any character to exit return 0; // indicate successful termination } // end main
// constructor fill vector with random integers MergeSort::MergeSort( int vectorSize ) { size = ( vectorSize > 0 ? vectorSize : 10 ); // validate vectorSize srand( time( 0 ) ); // seed random number generator using current time // fill vector with random ints in range 10-99 for ( int i = 0; i < size; i++ ) data.push_back( 10 + rand() % 90 ); } // end MergeSort constructor
int nrand(const int n) { if (n <= 0 || n > RAND_MAX) { throw domain_error("Argument to nrand is out of range."); } time_t t = time(nullptr); srand(t); const int r = rand() % n; cout << "r = " << r << endl; return r; }
int main(int argc, char* argv[]) { MPI_Status status; int rank, size, color, errs=0; //double START; string readfilename = "pg100.txt"; MPI_Init(&argc, &argv); MPI_Comm_rank( MPI_COMM_WORLD, &rank ); MPI_Comm_size(MPI_COMM_WORLD, &size); srand((unsigned)time(NULL) + rank*100); //START = MPI_Wtime(); // búum til com fyrir hópana MPI_Group mappers, partitioners, reducers, everyone; MPI_Comm mapparacom, partararcomm, reddararcomm; MPI_Comm_group(MPI_COMM_WORLD, &everyone); // ákveðum MPI_Group_incl(everyone, 2, &mapparar[0], &mappers); MPI_Comm_create(MPI_COMM_WORLD, mappers, &mapparacom); MPI_Group_incl(everyone, 2, &partarar[0], &partitioners); MPI_Comm_create(MPI_COMM_WORLD, partitioners, &partararcomm); MPI_Group_incl(everyone, 2, &reddarar[0], &reducers); MPI_Comm_create(MPI_COMM_WORLD, reducers, &reddararcomm); cout << "DONE creating groups and comms" << endl; if (rank < MAX_MAPP_ID) { mapper(reddararcomm, rank, readfilename); } else if (rank < MAX_PART_ID) { reducer(mapparacom, rank); } else { partitioner(partararcomm, rank); } cout << "Node " << rank << " stopping." << endl; MPI_Barrier(MPI_COMM_WORLD); cout << "Node " << rank << " stopped." << endl; MPI_Finalize(); }
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); }
void App::setup() { using std::srand; using std::time; srand(time(nullptr)); hideCursor(); setFpsSampleInterval(1.f); m_Timer.start(); BuildGame(*this); }
//起始乱序分牌 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; } }
void TimerThread::startTimer(unsigned min) { const time_t startTime = time(NULL); const time_t endTime = startTime + (min * 60); while((time(NULL) < endTime) && __timerEnabled) { sleep(1); time_t timeSpent = time(NULL) - startTime; float timeSpentPercent = (float)timeSpent/(min * 60) * 100; int remainingTime = (min * 60) - timeSpent; int remainingMin = remainingTime / 60; int remainingSec = remainingTime % 60; emit progressChanged(timeSpentPercent); emit remainingMinutesUpdated(remainingMin); emit remainingSecondsUpdated(remainingSec); } }
/* Purpose: To shuffle the cards in the Deck once Entry: N/A Exit: The cards in the deck have now been placed in a random order */ void Deck::Shuffle() { srand(static_cast<int>(time(0))); cout << "Will shuffle one time." << endl; for(int i = 0; i < MAX_NUMBER_OF_CARDS; i++) { int RandomNumber = rand() % MAX_NUMBER_OF_CARDS; Card Temp = m_Deck[i]; m_Deck[i] = m_Deck[RandomNumber]; m_Deck[RandomNumber] = Temp; } }
ColoredCubeApp::ColoredCubeApp(HINSTANCE hInstance) : D3DApp(hInstance), mFX(0), mTech(0), mVertexLayout(0), mfxWVPVar(0), mTheta(0.0f), mPhi(PI*0.25f) { srand(time(0)); D3DXMatrixIdentity(&mView); D3DXMatrixIdentity(&mProj); D3DXMatrixIdentity(&mWVP); D3DXMatrixIdentity(&mVP); score = 0; firstpass = true; startScreen = true; endScreen = false; }
/*============================================================================= Purpose: To shuffle the cards in the Deck into some random order. =============================================================================*/ void Deck::Shuffle() { srand(static_cast<int>(time(0))); for(int i = 0; i < MAX_NUMBER_OF_CARDS; i++) { int RandomNumber = rand() % MAX_NUMBER_OF_CARDS; Card Temp = m_Deck[i]; m_Deck[i] = m_Deck[RandomNumber]; m_Deck[RandomNumber] = Temp; } m_Current_Card = 0; }
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(NULL) ); // seed random generator int maxCount = 10; // maximal number of answer counts int count = 0; // count anwsers int countCorrect = 0; // count correct answers int countWrong = 0; // count wrong anwsers while( count < maxCount ) { int number1 = generateNumber(); // generate one number int number2 = generateNumber(); // generate second number int correctResult = -1; correctResult = number1 * number2; // correct multiplication result // display which numbers are being multiplyed // To exit loop, input 0 displayMessage( number1, number2 ); int userResult = -1; // user result of multiplication cin >> userResult; // read input // repeat until result is correct while( userResult != correctResult ) { ++countWrong; // count wrong anwsers ++count; // count anwsers displayAfterWrongAnswer(); cin >> userResult; } // display message for correct result if( userResult == correctResult ) { ++count; ++countCorrect; displayAfterCorrectAnswer(); } } if( count != maxCount ) cout << "Not correct counting!" << endl; // display statistics statistics( count, countCorrect ); return 0; }// end main function
// this method creates new numbers and puts them in the vector numbers void create() { // new random seed srand(time(NULL)); while (running) { // creating a random number between 1 and 1000 int random = rand() % 1000 + 1; // locking the mutex m.lock(); cout << "Creator: Random number " << random << endl; // putting the number numbers.push_back(random); m.unlock(); // sleeps for 300 milliseconds before creating a new number sleep_for(milliseconds(300)); } }
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); }
int main() { enum Status {CONTINUE, WON, LOST}; int myPoint; Status gameStatus; srand(time(0)); int sumOfDice = rollDice(); switch (sumOfDice) { case 7: case 11: gameStatus = WON; break; case 2: case 3: case 12: gameStatus = LOST; break; default: gameStatus = CONTINUE; myPoint = sumOfDice; cout << "Point is " << myPoint << endl; break; } while (gameStatus == CONTINUE) { sumOfDice = rollDice(); if (sumOfDice == myPoint) gameStatus = WON; else if(sumOfDice == 7) gameStatus = LOST; } if (gameStatus == WON) cout << "Player wins" << endl; else cout << "Player loses" << endl; return 0; }
//------------------------------------------------------------------------------ int main(void) { my1TestBot cTestBot; int count = 0; srand(time(0x0)); // main drive loop while(1) { cTestBot.CaptureView(); cTestBot.ColorDirect(); cTestBot.CaptureSens(); cTestBot.Evaluate(); if(cTestBot.ZeroDrive()) break; cTestBot.MoveDrive(); count++; if(count==MAX_COUNT) break; } return 0; }
int main(int argc, char *argv[]) { srand(time(NULL)); FILE *fd; static size_t rand_num; static long rand_min = 0L; static long rand_max = 1000000L; fd = fopen("unsorted.txt", "w"); switch(argc) { case 2: rand_num = atol(argv[1]); break; case 3: rand_num = atol(argv[1]); rand_max = atol(argv[2]); break; case 4: rand_num = atol(argv[1]); rand_min = atol(argv[2]); rand_max = atol(argv[3]); break; default: printf("Usage: %s rand_num\n", argv[0]); printf("Usage: %s rand_num rand_max\n", argv[0]); printf("Usage: %s rand_num rand_min rand_max\n", argv[0]); break; }//switch for(int i = 1; i <= rand_num; ++i) { if(i % 10 == 0) fputc('\n', fd); fprintf(fd, "%ld ", (long)(rand() * (rand_max - rand_min)/RAND_MAX +rand_min)); }//for fclose(fd); return 0; }//main
int main() { const int arraySize = 7; // ignore element zero int frequency[ arraySize ] = {}; // initialize elements to 0 srand( time( 0 ) ); // seed random number generator // roll die 6,000,000 times; use die value as frequency index for ( int roll = 1; roll <= 6000000; roll++ ) frequency[ 1 + rand() % 6 ]++; cout << "Face" << setw( 13 ) << "Frequency" << endl; // output each array element's value for ( int face = 1; face < arraySize; face++ ) cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ] << endl; return 0; // indicates successful termination } // end main
bool PfffFindDuplicatesOptionManager::validate() { if (help) return true; try { if (parameters.size() == 0) throw (char*)"Error: No files to process."; if (!key_given) { srand ( time(NULL) ); key = rand(); } if (http_given && ftp_given) throw (char*)"Error: Both HTTP and FTP may not be requested."; // Set default port if (!port_given) { if (http_given) port = 80; else if (ftp_given) port = 21; } // If we're using ftp and haven't specified request_cost, set a // reasonable default. if (!request_cost_given && ftp_given) request_cost = 1024000; // Now fill in the options structure pfff_options_init(&options, key); options.block_count = block_count; options.block_size = block_size; options.header_block_count = header_block_count; options.without_replacement = without_replacement; options.with_size = with_size; options.no_prefix = true; options.no_filename = true; char* errmsg; if (pfff_options_validate(&options, &errmsg)) return true; else throw errmsg; } catch(char* msg) { error_message = string(msg); return false; } }
int main() { srand( time(0) ); // seed generator const int nNumOfDiceToss = 10000; // number of tossing die int an2Dice[ nNumOfDiceToss ]; // array of two dice sum // simulate two rolling dices for ( int roll = 0; roll < nNumOfDiceToss; ++roll ) { int nDie1 = nRollDie(); // first dice rolling int nDie2 = nRollDie(); // second dice rolling an2Dice[ roll ] = nDie1 + nDie2; } // count frequency for two dice toss int anDiceFreq[ 13 ] = {}; for ( int roll = 0; roll < nNumOfDiceToss; ++roll ) ++anDiceFreq[ an2Dice[ roll ] ]; // total sum of rolling dice int nTotalSum = 0; for ( int i = 0; i < 13; ++i ) nTotalSum += anDiceFreq[ i ]; // display frequency of two dices cout << setw(2) << "n" << setw(7) << "freq" << setw(7) << "ratio" << endl; for ( int freq = 2; freq < 13; ++freq ) { // probability const double nProb = static_cast<double>( anDiceFreq[ freq ] ) / nTotalSum; cout << setw(2) << freq << ":" << setw(7) << anDiceFreq[ freq ] << fixed << setprecision(2) << setw(7) << nProb << endl; } return 0; }//end main
int main (int argc, char **argv) { selectScenario(); srand(time(0)); //! Initialized the node, setup the NodeHandle //! for handling the communication with the ROS system ros::init(argc, argv, "hmc_sub"); ros::NodeHandle nh; //! Define the subscriber to the person's gesture ros::Subscriber sub = nh.subscribe ("/swgesture", 1, baxterCallback); //! Define the publisher to send the desired robot's gesture pub = nh.advertise<std_msgs::Int32> ("/bxpoint_d", 1); ros::spin(); return 0; }
// begin program execution with main function int main() { // Every time program runs, different seed is used, based // on computer time (current time) srand( time(NULL) ); int number = 0; int guess = 0; // guessed number int count = 0; // count number of guess number = genNumber(); // generated random number displayMessage(); // display information do{ cin >> guess; // read input number ++count; // count number of guesses if (guess > number) { cout << "To high. Try again." << endl; } else if (guess < number) { cout << "To low. Try again." << endl; } else { displayGuessMessage( count ); // display message based on count number cout << "Excellent! You guessed the number!" << endl << "Would you like to play again (y or n)? "; char answer; cin >> answer; if (answer == 'y') // play again { number = genNumber(); displayMessage(); } } } while( guess != number ); return 0; }// end main function
int main() { srand( time(NULL) ); // initialize seed with time // Count number of tails and heads of the coin side int tailCount = 0; int headCount = 0; for (int i = 0; i < 100; ++i) { if ( flip() ) { // coin side head ++headCount; } else { // coin side tail ++tailCount; } } // Display number of tails and heads count cout << "Tails: " << tailCount << endl; cout << "Heads: " << headCount << endl; return 0; }