[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppRandomShuffle

(C++) std::random_shuffle

Function to shuffle an array or vector. Can be found in the STL header file algorithm.h.

  1. include <iostream>
  2. include <vector>
  3. include <algorithm>
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; }


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.

  1. include <iostream>
  2. include <vector>
  3. include <algorithm>
  4. include <numeric>
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; } }


Code links



last edited (November 16, 2006) by bilderbikkel, Number of views: 2693, Current Rev: 5 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.