[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppRandomShuffle
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppRandomShuffle
(C++) std::random_shuffle
Function to shuffle an array or vector. Can be found in the STL header file algorithm.h.int main() { const int size = 5; std::vector<int> myVector(size); for (int i=0; i!=size; ++i) myVector[i]=i; std::cout << "Vector before shuffling: " << std::endl; for (int i=0; i!=size; ++i) std::cout << i << " : " << myVector[i] << std::endl; std::random_shuffle(myVector.begin(), myVector.end()); std::cout << "Vector after shuffling: " << std::endl; for (int i=0; i!=size; ++i) std::cout << i << " : " << myVector[i] << std::endl; }
- include <iostream>
- include <vector>
- include <algorithm>
Testing std::random_shuffle
How random does std::random_shuffle shuffle? Here is a test giving the impression it does a pretty nice job, although I does not include any statistics.std::vector<double> getInitVector(const int& size) { std::vector<double> v(size); for (int i=0; i<size; ++i) v[i] = i; return v; } int main() { const int size = 100; const int nTests = 10000; const std::vector<double> vOrig = getInitVector(size); const double average = std::accumulate(vOrig.begin(),vOrig.end(),0.0) / static_cast<double>(size); //Start the tests std::vector<double> sums(size,0.0); for (int i=0; i<nTests; ++i) { std::vector<double> vCopy(vOrig); std::random_shuffle(vCopy.begin(), vCopy.end()); for (int j=0; j<size; ++j) { sums[j] += vCopy[j]; } } std::cout << "Expected value: " << average * nTests << std::endl; for (int i=0; i!=size; ++i) { std::cout << i << " : " << sums[i] << std::endl; } }
- include <iostream>
- include <vector>
- include <algorithm>
- include <numeric>
Code links
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
