Fill in a vector with random values (Language C)

3

In one more of my studies in Language C, I had the idea of trying to populate a dynamically allocated vector with random numbers. However, I came across the following problem: The rand function was set to randomize a number every second. As the fill speed is too fast, the "for" ends up filling that vector in less than a second, so all the values entered are exactly the same.

My knowledge in the area is still very limited, so at the moment I could not find any solution for this. What I do know is that I could get the srand out of my code. But it would generate the same numbers every time I rebooted it.

Would anyone have an idea? And if I had, could you explain it to me? I'm a beginner. So it's important that I understand the process.

Thank you in advance!

#include "stdio.h"
#include "stdlib.h"
#include "time.h"

int main()
{
	int k = NULL, *matriz = NULL;


	printf("Tamanho do vetor: ");
	scanf("%i", &k);

	matriz = (int *)malloc(k * sizeof(int));

	for (int i = 0; i < k; i++)
	{
		srand(time(NULL));
		matriz[i] = rand() % k + 1;

		printf("Valor  %i : %i" , i+1,  matriz[i]);
		printf("\n");
	}

	system("pause");
	return 0;
}
    
asked by anonymous 21.04.2015 / 17:12

1 answer

5

The problem is in the following line:

srand(time(NULL));

The function time(NULL) has a resolution in seconds, that is, if you call it several times within a second, the value returned will always be the same.

So you have the problem of putting the seed of rand (through srand(time(NULL) ) always in the same value, which means that the generated values are always equal. Essentially, if loop is fast it has the equivalent of srand(1) .

From documentation :

  

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.

To resolve the problem, change srand(time(NULL) out of loop :

srand(time(NULL));
for (int i = 0; i < k; i++)
{
    matriz[i] = rand() % k + 1;

    printf("Valor  %i : %i" , i+1,  matriz[i]);
    printf("\n");
}

In this way, the numbers generated will be different.

    
21.04.2015 / 17:25