Skip to content

Instantly share code, notes, and snippets.

@tmadlener
Last active June 12, 2017 15:33
Show Gist options
  • Save tmadlener/1c193f7e8096629e42ec0de214f04cc0 to your computer and use it in GitHub Desktop.
Save tmadlener/1c193f7e8096629e42ec0de214f04cc0 to your computer and use it in GitHub Desktop.
randomly shuffle entries of a vector
#include <vector>
#include <random>
#include <algorithm>
#include <iostream>
#include "TRandom3.h"
// g++ -std=c++11 shuffle_vec.cc $(root-config --libs --cflags)
// for a non-c++11 compliant version this function can be used instead of the lambda defined below in main
// for std::random_shuffle (std::shuffle has been introduced in c++11 only)
inline int rootGetRandom(const int N)
{
return gRandom->Integer(N);
}
int main()
{
std::vector<int> vec;
vec.reserve(100);
for (int i = 0; i < 100; ++i) { vec.push_back(i); }
std::vector<int> vec2{vec};
// using std::shuffle
std::mt19937 rng(std::random_device{}());
std::shuffle(vec.begin(), vec.end(), rng);
// using std::random_shuffle and the mersenne twister from ROOT
if (gRandom) delete gRandom;
gRandom = new TRandom3(std::random_device{}());
auto rootRNG = [&gRandom](const int N) { return gRandom->Integer(N); };
std::random_shuffle(vec2.begin(), vec2.end(), rootRNG);
for (const auto& v : vec) std::cout << v << " ";
std::cout << "\n";
for (const auto& v : vec2) std::cout << v << " ";
std::cout << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment