Last active
February 28, 2018 10:29
-
-
Save rexlow/20f567959e69cd8a4b94c3b87104c039 to your computer and use it in GitHub Desktop.
Random Permutation in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// random_shuffle example | |
#include <iostream> // std::cout | |
#include <algorithm> // std::random_shuffle | |
#include <vector> // std::vector | |
#include <ctime> // std::time | |
#include <cstdlib> // std::rand, std::srand | |
using namespace std; | |
const int SIZE = 5; | |
// random generator function: | |
int generateSeed (int i) { | |
return rand() % i; | |
} | |
int * randPerm() { | |
static int arr[SIZE]; | |
// srand - produce a seed value (randomness) | |
// https://stackoverflow.com/a/4736527/9049053 | |
srand ( unsigned ( time(0) ) ); | |
// create a vector | |
vector<int> myvector; | |
// push some value (0-4) into the vector | |
for (int i=0; i<SIZE; i++) { | |
myvector.push_back(i); | |
} | |
// shuffle all elements inside the vector | |
random_shuffle(myvector.begin(), myvector.end()); | |
// if we run this program more than 1 time, we will find that every time the vector will be same | |
// so we pass in a random number to make sure it is really random | |
// try to comment out this line so see what I mean | |
random_shuffle(myvector.begin(), myvector.end(), generateSeed); | |
// convert vector to an array (we want to return an array) | |
copy(myvector.begin(), myvector.end(), arr); | |
return arr; | |
} | |
int main () { | |
int *permArray = randPerm(); | |
for (int i=0; i<SIZE; i++) { | |
cout << permArray[i] << ' '; | |
} | |
cout << "\n"; | |
int *permArray2 = randPerm(); | |
for (int i=0; i<SIZE; i++) { | |
cout << permArray2[i] << ' '; | |
} | |
cout << "\n"; | |
int *permArray3 = randPerm(); | |
for (int i=0; i<SIZE; i++) { | |
cout << permArray3[i] << ' '; | |
} | |
cout << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment