Created
November 21, 2011 17:22
-
-
Save aprell/1383298 to your computer and use it in GitHub Desktop.
Fisher-Yates array shuffle
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 <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