Wednesday 15 February 2012

C++ How can I shuffle a vector without using the shuffle functions from the standard library? -



C++ How can I shuffle a vector without using the shuffle functions from the standard library? -

for odd reason, have assignment shuffle contents of vector without using shuffle or random_shuffle functions available in c++ standard library. next basic code (non-functioning) function job give clearer thought of i'm getting at:

#include <iostream> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; // shuffle vector function: void shuffle_vector(std::vector<string> &names) { } // end function int main(void) { srand(time(0)); vector<string> names; names.push_back("sally"); names.push_back("sue"); names.push_back("bob"); names.push_back("fred"); cout << "your names:" << endl; (int = 0; < names.size(); i++) { cout << + 1 << ". " << names[i] << endl; } cout << "press come in shuffle."; cin.get(); shuffle_vector(names); cout << "\nyour shuffled names:" << endl; (int = 0; < names.size(); i++) { cout << + 1 << ". " << names[i] << endl; } cin.get(); }

the way thought to:

"push_back" vector create temporary spot randomly assign index temporary spot randomly assign index newly-empty spot put index in temporary spot lastly remaining empty index "pop_back" vector original size

(like switching indexes in arrays)

i don't know how execute also--more importantly--if work or if it's best way go it. how it?

bam! pretty fun figure out!

i used rand , "for" loop iterated 100 times randomize it. added "temporary" index deleted after shuffling complete.

#include <iostream> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; // shuffle vector function: void shuffle_vector(std::vector<string> &names) { (int = 0; < 100; i++) { int randomindex = rand() % names.size(); int randomindex2 = rand() % names.size(); if (randomindex2 == randomindex) // create sure 2 random values aren't same { { randomindex2 = rand() % names.size(); } while (randomindex2 == randomindex); } names.push_back("temporary"); // create temporary index @ end of vector int last_index_number = (names.size() - 1); names[last_index_number] = names[randomindex]; names[randomindex] = names[randomindex2]; names[randomindex2] = names[last_index_number]; names.pop_back(); // bring vector original size } } // end function int main(void) { srand(time(0)); vector<string> names; names.push_back("sally"); names.push_back("sue"); names.push_back("bob"); names.push_back("fred"); cout << "your names:" << endl; (int = 0; < names.size(); i++) { cout << + 1 << ". " << names[i] << endl; } cout << "press come in shuffle."; cin.get(); shuffle_vector(names); cout << "\nyour shuffled names:" << endl; (int = 0; < names.size(); i++) { cout << + 1 << ". " << names[i] << endl; } cin.get(); }

c++ vector

No comments:

Post a Comment