Last active
August 29, 2015 14:15
-
-
Save tamanobi/5768ef1466bbe9fafa64 to your computer and use it in GitHub Desktop.
Knuth Shuffle(Fisher-Yates Shuffle)を実装。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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