I was trying to generate a random array of integers of length 16 inside a loop. The elements of the array will lie inside [0, 255]. I thought assigning random integers from [0, 255] would suffice; but it does not work (one random array is created which remains unchanged over iterations). Then I tried shuffling, but the situation does not improve (I also notice that the probability of 0 in the 'random' array is significantly larger).
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//#define Shuffle
/* Generate a random integer array of length `size` with elements from [0, 255] */
int* random_sample(int size)
{
int i, j, k;
int *elements = malloc(size*sizeof(int));
/* Assign random integers */
for (i = size - 1; i > 0; --i)
{
elements[i] = rand() % 256;
}
/* Shuffle */
#ifdef Shuffle
for (i = size - 1; i > 0; --i) {
j = rand() % size;
k = elements[i];
elements[i] = elements[j];
elements[j] = k;
}
#endif
return elements;
}
int main(int argc, char const *argv[])
{
int LENGTH = 16, i, iteration;
int *random_array = random_sample(LENGTH);
srand(time(NULL));
for (iteration = 0; iteration < 10; ++iteration)
{
for (i = 0; i < LENGTH; ++i)
printf("%d, ", random_array[i]);
puts("");
}
return 0;
}
A typical output looks like:
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
0, 227, 251, 242, 171, 186, 205, 41, 236, 74, 255, 81, 115, 105, 198, 103,
I tried several variations of the above code, but none of them works. Need help!
EDIT
I was trying variations of the code, and mistakenly printed the same unchanged array (as pointed out by some others - thanks to them); originally I wrote
int main(int argc, char const *argv[])
{
int LENGTH = 16, i, iteration;
int *random_array;
srand(time(NULL));
for (iteration = 0; iteration < 10; ++iteration)
{
random_array = random_sample(LENGTH);
for (i = 0; i < LENGTH; ++i)
printf("%d, ", random_array[i]);
puts("");
}
return 0;
}
which print much more 0s.
EDIT (2)
Thanks to @pmg, I found the problem. Inside random_sample function, changing the first
for (i = size - 1; i > 0; --i) to for (i = size - 1; i >= 0; --i) works fine!
Thank you all.
random_sample()once. Inside the function you never assign toelements[0]. Use the standard for loop construct:for (i = 0; i < LENGTH, i++) /* ... */;; you don't need to deviate from the norm.