Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffle(int *a, int size) {
for (int i = size; i > 1; ) {
int r = rand() % i--;
int t = a[r]; a[r] = a[i]; a[i] = t;
}
}
int main() {
srand(time(NULL));
int n;
printf("Length of permutation: ");
scanf("%d", &n);
int *per = calloc(n + 1, sizeof *per); if (!per) { perror("calloc"); exit(0); }
for (int i = 1; i <= n; ++i) per[i] = i; // first element unused
shuffle(per + 1, n); // don't pass first element to shuffle
int *pos = calloc(n + 1, sizeof *pos); if (!pos) { perror("calloc"); exit(0); }
for (int i = 1; i <= n; ++i) pos[per[i]] = i;
for (int i = 1; i <= n; ++i) printf("%2d ", i); putchar('\n');
for (int i = 1; i <= n; ++i) printf("%2d ", per[i]); putchar('\n');
for (int i = 1; i <= n; ++i) printf("%2d ", pos[i]); putchar('\n');
free(pos);
free(per);
return 0;
}
Code:
Length of permutation: 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
7 1 4 3 13 2 19 16 17 20 10 9 14 18 5 11 12 6 15 8
2 6 4 3 15 18 1 20 12 11 16 17 5 13 19 8 9 14 7 10