Fill a vector with random values (C language)

Asked

Viewed 18,229 times

3

In another of my studies in the C language, I had the idea of trying to fill 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 filling speed is too fast, the "for" ends up filling this vector in less than a second, and therefore, all inserted values are exactly equal.

My knowledge in the area is still quite limited, so at the moment I could not find any solution to this. What I know is that I could take srand out of my code. But it would generate the same numbers every time I restart its execution.

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

Thanks 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;
}

1 answer

5


The problem is in the following line:

srand(time(NULL));

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

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

Of documentation:

Two Different initializations with the same Seed will generate the same Succession of Results in subsequent calls to Rand.

To solve the problem, change the srand(time(NULL) out of the 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.

  • 1

    Wow, thanks Omni! This really solved the problem and got much better and faster than the conditions I had entered. After all, he explained it well! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.