Skip to content

Instantly share code, notes, and snippets.

@gcardone
Created September 30, 2013 00:23
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 gcardone/6757817 to your computer and use it in GitHub Desktop.
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).
#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