Skip to content

Instantly share code, notes, and snippets.

@aprell
Created November 21, 2011 17:22
Show Gist options
  • Save aprell/1383298 to your computer and use it in GitHub Desktop.
Save aprell/1383298 to your computer and use it in GitHub Desktop.
Fisher-Yates array shuffle
#include <stdio.h>
#include <stdlib.h>
#define N 10
static int A[N];
static unsigned int seed;
static void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
// Fisher-Yates shuffle
static void shuffle(int *A, int len)
{
int rand, i;
for (i = len-1; i > 0; i--) {
rand = rand_r(&seed) % (i + 1);
swap(&A[rand], &A[i]);
}
}
int main(void)
{
int i;
for (i = 0; i < N; i++) {
A[i] = i;
printf("A[%d] = %d\n", i, A[i]);
}
printf("\n");
seed = 100;
shuffle(A, N);
for (i = 0; i < N; i++) {
printf("A[%d] = %d\n", i, A[i]);
}
printf("\n");
shuffle(A, N);
for (i = 0; i < N; i++) {
printf("A[%d] = %d\n", i, A[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment