Created
September 30, 2013 00:23
-
-
Save gcardone/6757817 to your computer and use it in GitHub Desktop.
How to shuffle an array using the Fisher-Yates shuffle (also known as the Knuth shuffle: The Art of Computer Programming volume 2: Seminumerical algorithms, Algorithm P).
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 <algorithm> | |
#include <cstdlib> | |
#include <iterator> | |
#include <iostream> | |
#ifndef N | |
#define N 100 | |
#endif | |
inline int rand_range(int min, int max) { | |
return min + rand() / (RAND_MAX / (max - min + 1) + 1); | |
} | |
int main() { | |
int data[N]; | |
srand(time(0)); | |
for (int i = 0; i < N; i++) { | |
data[i] = i; | |
} | |
std::cout << "Data before the shuffle" << std::endl; | |
std::copy(data, data+N, std::ostream_iterator<int>(std::cout,", ")); | |
std::cout << std::endl; | |
// Shuffle the data array according to the Fisher-Yates shuffle | |
for (int i = (N - 1); i > 0; --i) { | |
int j = rand_range(0, i); | |
int temp; | |
temp = data[j]; | |
data[j] = data[i]; | |
data[i] = temp; | |
} | |
std::cout << std::endl << "Data after the shuffle" << std::endl; | |
std::copy(data, data+N, std::ostream_iterator<int>(std::cout,", ")); | |
std::cout << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment