Skip to content

Instantly share code, notes, and snippets.

@matwey
Last active February 12, 2019 14:01
Show Gist options
  • Select an option

  • Save matwey/bf6c2b45100b778bfb4ea528e7a62c18 to your computer and use it in GitHub Desktop.

Select an option

Save matwey/bf6c2b45100b778bfb4ea528e7a62c18 to your computer and use it in GitHub Desktop.
c++ partial_shuffle
#include <iostream>
#include <cstring>
#include <random>
#include <chrono>
#include <iterator>
template<class RandomIt, class URBG>
void partial_shuffle(RandomIt first, RandomIt middle, RandomIt last, URBG&& g)
{
using difference_type = typename std::iterator_traits<RandomIt>::difference_type;
using value_type = typename std::make_unsigned<difference_type>::type;
using distribution_type = std::uniform_int_distribution<value_type>;
using param_type = typename distribution_type::param_type;
if (first == middle)
return;
distribution_type d;
for (auto it = first; it != middle; ++it) {
std::iter_swap(it, first + d(g, param_type(it - first, last - first - 1)));
}
}
int main(int argc, char** argv) {
std::random_device rd;
const int x[] = {0,1,2,3,4,5,6,7,8,9};
int z[10];
int p[10][10];
std::memset(p, 0, sizeof(p));
for (int i = 0; i < 1000000; i++) {
std::copy(x, x+sizeof(x)/sizeof(x[0]), z);
partial_shuffle(z, z+3, z+sizeof(z)/sizeof(z[0]), rd);
for (int j = 0; j < 10; j++) {
p[j][z[j]]++;
}
}
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 10; i++) {
std::cout << p[j][i] << " ";
}
std::cout << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment