Created
August 6, 2016 00:22
-
-
Save 3ki5tj/171fc89d86cd11a0795207a5c5f8db5c to your computer and use it in GitHub Desktop.
Random permutation
This file contains hidden or 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> | |
#include <time.h> | |
/* generate a random permutation of array `a` in place */ | |
static void randperm(int n, double *a) | |
{ | |
int i, j; | |
double x; | |
for ( i = 0; i < n - 1; i++ ) { | |
j = i + (int) ( (n - i) * rand() / RAND_MAX ); | |
/* swap a[j] and a[i] */ | |
x = a[j], a[j] = a[i], a[i] = x; | |
} | |
} | |
static void print(int n, const double *a) | |
{ | |
int i; | |
for ( i = 0; i < n; i++ ) | |
printf("%g ", a[i]); | |
printf("\n"); | |
} | |
int main(void) | |
{ | |
int n = 5, k; | |
double a[] = {1, 4, 3, 5, 2}; | |
srand( time(NULL) ); | |
for ( k = 0; k < 20; k++ ) { | |
randperm(n, a); | |
print(n, a); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment