0% found this document useful (0 votes)
4 views2 pages

Generate Random Permutations in C

This C program generates random permutations of arrays of specified sizes. It initializes arrays with values from 1 to the size, shuffles them, and prints a sample of the first 10 elements for the first array generated. The program handles multiple sizes and allocates memory dynamically for each array before freeing it after use.

Uploaded by

subir paul
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Generate Random Permutations in C

This C program generates random permutations of arrays of specified sizes. It initializes arrays with values from 1 to the size, shuffles them, and prints a sample of the first 10 elements for the first array generated. The program handles multiple sizes and allocates memory dynamically for each array before freeing it after use.

Uploaded by

subir paul
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

h>
#include <stdlib.h>
#include <time.h>

void generate_permutation(int *array, int size) {


// Initialize the array with values from 1 to size
for (int i = 0; i < size; i++) {
array[i] = i + 1;
}

// Shuffle the array to create a random permutation


for (int i = size - 1; i > 0; i--) {
int j = rand() % (i + 1); // Generate a random index
int temp = array[i]; // Swap array[i] and array[j]
array[i] = array[j];
array[j] = temp;
}
}

void generate_and_print_arrays(int sizes[], int num_sizes, int num_arrays) {


for (int k = 0; k < num_sizes; k++) {
int size = sizes[k];
printf("Generating %d arrays of size %d...\n", num_arrays, size);

for (int n = 0; n < num_arrays; n++) {


// Allocate memory for the array
int *array = (int *)malloc(size * sizeof(int));
if (array == NULL) {
fprintf(stderr, "Memory allocation failed for size %d\n", size);
exit(EXIT_FAILURE);
}

// Generate the random permutation


generate_permutation(array, size);

// Print the first 10 elements of the first array as an example


if (n == 0) {
printf("Sample Array (size %d): ", size);
for (int i = 0; i < 10; i++) {
printf("%d ", array[i]);
}
printf("...\n");
}

// Free the allocated memory


free(array);
}
}
}

int main() {
// Define the sizes of the arrays
int sizes[] = {10000, 100000, 1000000, 10000000};
int num_sizes = sizeof(sizes) / sizeof(sizes[0]);
int num_arrays = 100;

// Seed the random number generator


srand(time(NULL));
// Generate and print arrays
generate_and_print_arrays(sizes, num_sizes, num_arrays);

return 0;
}

You might also like