Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created August 14, 2015 16:33
Show Gist options
  • Select an option

  • Save davepkennedy/f9a8be8a1053bd098519 to your computer and use it in GitHub Desktop.

Select an option

Save davepkennedy/f9a8be8a1053bd098519 to your computer and use it in GitHub Desktop.
Shuffling in C/C++
#include <iostream>
#include <cstdlib>
using namespace std;
// From http://stackoverflow.com/questions/2509679/how-to-generate-a-random-number-from-within-a-range
long random_at_most(long max) {
unsigned long
// max <= RAND_MAX < ULONG_MAX, so this is okay.
num_bins = (unsigned long) max + 1,
num_rand = (unsigned long) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
long x;
do {
x = random();
}
// This is carefully written not to overflow
while (num_rand - defect <= (unsigned long)x);
// Truncated division is intentional
return x/bin_size;
}
void swap (int& a, int& b) {
int t = a;
a = b;
b = t;
}
void shuffle (int* values, size_t length) {
for (size_t i = 0; i < length; i++) {
size_t idx = random_at_most(length - i);
swap(values[i], values[idx]);
}
}
void demo () {
int values [] = {1,2,3,4,5,6,7,8,9};
shuffle(values, 9);
for (int i = 0; i < 9; i++) {
printf("%d ", values[i]);
}
}
int main(int argc, const char * argv[]) {
// insert code here...
for (int i = 0; i < 10; i++) {
demo();
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment