Skip to content

Instantly share code, notes, and snippets.

@stefanobaghino
Last active November 3, 2023 16:18
Show Gist options
  • Save stefanobaghino/7d411ef4d3a2ab548fceeb59f013b784 to your computer and use it in GitHub Desktop.
Save stefanobaghino/7d411ef4d3a2ab548fceeb59f013b784 to your computer and use it in GitHub Desktop.
Shuffle an array
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffle(int array[], size_t n) {
if (n > 1) {
size_t i;
for (i = n - 1; i > 0; i--) {
size_t j = rand() % (i + 1);
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
}
void test_uniformity() {
int counts[5] = {0, 0, 0, 0, 0};
for (int i = 0; i < 1e8; i++) {
// always start from the same array to measure uniformity
int ns[] = {1, 2, 3, 4, 5};
shuffle(ns, 5);
for (int j = 0; j < 5; j++) {
counts[j] += ns[j];
}
}
int min = counts[0];
int max = counts[0];
for (int i = 0; i < 5; i++) {
if (counts[i] < min) {
min = counts[i];
}
if (counts[i] > max) {
max = counts[i];
}
}
double ratio = (double) max / min;
printf("test_uniformity: %f (0 = perfect)\n", ratio - 1);
}
void test_performance() {
struct timespec start_time, end_time;
// initialize only once to measure performance
int ns[] = {1, 2, 3, 4, 5};
int ops = 1e8;
int start = clock();
for (int i = 0; i < ops; i++) {
shuffle(ns, 5);
}
int end = clock();
double sec_tot = (double) (end - start) / CLOCKS_PER_SEC;
double nsec_op = sec_tot / ops * 1e9;
printf("test_performance: %fns/op (%fs overall)\n", nsec_op, sec_tot);
}
int main() {
srand(time(NULL)); // seed the rng
test_uniformity();
test_performance();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment