randomize an array in c code example
Example 1: How to generate a random array in c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main(){
int vet[1000], fre[50];
int i;
srand(time(NULL));
for(i=0;i<1000;i++){
vet[i]=(rand()%51);
}
for(i=0;i<1000;i++){
printf("%d\n", vet[i]);
}
for(i=0;i<1000;i++){
fre[vet[i]]=fre[vet[i]]+1;
}
for(i=0;i<51;i++){
printf("The number %d was generated %d times\n", i, fre[i]);
}
}
Example 2: how to shuffle array in c
#include <stdlib.h>
/* Arrange the N elements of ARRAY in random order.
Only effective if N is much smaller than RAND_MAX;
if this may not be the case, use a better random
number generator. */
void shuffle(int *array, size_t n)
{
if (n > 1)
{
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}