shuffle algorithm
-
Hi,
how can you implement the following?
How would you program a computer to shuffle a deck of cards (Generate a permutation of the numbers from 1 to 100, uniformly at random)Thanks,
Justin12
-
card cards[100]; for(int i = 99; i; --i) { //Generate a random number in the range from 0 to i //Exchange cards[i] and cards[generated random number] }
-
-
-
The approach, that Belli suggested is also known as Fisher-Yates shuffle. The mentioned
std::random_shuffle
uses this algorithm in some implementations.
-
#include <random> #include <algorithm> int main() { std::vector<int> v(100); std:iota(v.begin(), v.end,1); std::random_device rd; std::mt19937 g(rd()); std::shuffle(v.begin(), v.end(), g); }