Skip to content

Instantly share code, notes, and snippets.

@tamanobi
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamanobi/5768ef1466bbe9fafa64 to your computer and use it in GitHub Desktop.
Save tamanobi/5768ef1466bbe9fafa64 to your computer and use it in GitHub Desktop.
Knuth Shuffle(Fisher-Yates Shuffle)を実装。
#include <iostream>
#include <vector>
#include <random>
#include <cmath>
// knuth shuffle
void shuffle(std::vector<int>& ary){
std::random_device rd;
std::mt19937 mt(rd());
long N = ary.size();
for(long i = N-1; i >= 0; i--){
//long r = std::floor(mt()*(i+1));
std::uniform_int_distribution<> rnd(0, i);
long r = rnd(mt);
long t = ary[i];
ary[i] = ary[r];
ary[r] = t;
}
}
void showData(const std::vector<int>& ary){
for(auto el : ary){
std::cout << el << " ";
}
std::cout << std::endl;
}
int main(void){
using std::vector;
const long N = 1e1;
vector<int> ary(N);
//for(auto& el : ary) el = i
std::iota(begin(ary), end(ary), 1);
[&](){for(auto el:ary)std::cout<<el<<" "; std::cout<<std::endl;}();//C++11 practice
//showData(ary);
shuffle(ary);
showData(ary);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment