Skip to content

Instantly share code, notes, and snippets.

@3ki5tj
Created August 6, 2016 00:22
Show Gist options
  • Save 3ki5tj/171fc89d86cd11a0795207a5c5f8db5c to your computer and use it in GitHub Desktop.
Save 3ki5tj/171fc89d86cd11a0795207a5c5f8db5c to your computer and use it in GitHub Desktop.
Random permutation
#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