What this code is supposed to do is shuffle an array, nonetheless every time I run it on a I get the same "shuffled" array (of course by inputting the same un-shuffled array) I thought the srand(time(NULL)); part was going to make sure of that. If that is not it I don’t know how to make it really shuffle it.
So to sum up I need to know why my code is shuffling the array the same way every time.
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
# include <time.h>
int main(){
int n;
int m;
int tmp;
int i;
printf("Please input the number of elements in your array:\n");
scanf("%d", &n);
int baraja[n];
int tempbaraja[n];
for (int i = 0; i < (sizeof(baraja)/sizeof(baraja[0])); i ++){
printf("Please input the %d element of your array:\n",i);
scanf("%d",&baraja[i]);
}
printf("Unshuffled array:\n");
for (i=0;i < n;i++) {
printf(" %d \n",baraja[i]);
}
for (int i = 0; i < n; i ++){
tempbaraja[i] = baraja[i];
}
for (int i = 0; i < n; i ++){
srand(time(NULL));
m = rand() % n;
if (tempbaraja[m] == baraja[m]){
tmp = baraja[m];
baraja[m] = baraja[i];
baraja[i] = tmp;
}else{
}
}
printf("Shuffled array:\n");
for (i=0;i < n;i++) {
printf(" %d \n",baraja[i]);
}
}
You need to move srand(time(NULL)); outside the for loop.
If you see, rand() is a pseudo-random number generator. srand() is used to provide the seed based on which the random number will be generated by rand().
If every time you seed with the same time(NULL) before each call to rand(), each outcome of rand() is going to be the same.
To achieve the desired result, you need to seed the random number generator only once using srand() and later on each call of rand(), it will give you the random numbers.
Note: Though it is not mandatory, it's good practice to have an explicit return 0 at the end of main().
Get srand(time(NULL)) out of the loop.
From srand reference:
Two different initializations with the same seed will generate the
same succession of results in subsequent calls to rand.
So for each iteration you are initializing the random number generator and getting the first item, which is always the same.
You're misusing srand, it should only be called once outside of the loop. These is also a chance that the srand and rand implementations may be particularly bad on the platform you're running on, leading to poor performance if the program is re-executed quickly.
Alright, I'll answer the followup question. Why is srand() in a loop bad?
The rand() function produces a sequence of acceptably random numbers, without needing srand() at all. The problem is that it's a fixed sequence, so every time you run the program, you'll get the same set of "random" numbers.
The goal of srand(time(NULL)) is to pick a starting value different from any previous starting value. The time() function call is only being used to pick a different starting point, with the drawback that the result only changes once per second. Running the program twice in the same second can be a problem with programs launched from a script file or batch job, but usually not when launched from keyboard or mouse events.
So, using srand(time(NULL)) in the loop has one major evil effect. You only get one new random number every wall-clock second.
Even if you had a high-precision timer to sample from, or used:
unsigned counter = time(NULL);
srand(counter++);
..to choose a different starting value, there are still problems. The distribution of random number chosen from sequential starting points is not as "random" as the overall sequence, and may be quite bad for some generators. If you had a source of starting points that was random enough to give good result from srand();rand();, then you probably wouldn't need rand() at all. You could just use those starting values directly!
Finally, srand() slows down your program. Visual C++ in particular has notoriously slow rand() and srand(), and MinGW uses that library too. (The technical issue is due to storing the seed value in thread local storage, which takes over 100 instructions to find on each call.) However, even a statically linked non-thread-safe version involves an extra call and return that you don't need.
Those are the major reasons that I know of for not using srand() in a loop. Most developers would be happy with "it's not necessary".
The glibc srand() manual page, which states: "The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value." Specifically your program potentially violated the clause : "..sequences are repeatable by calling srand() with the same seed value." because it could seed rand() more than once per second with the time -- resulting in identical pseudo-random number sequences.
Related
This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 8 years ago.
I'm using the following code for generate the random numbers in C programming, but for every compilation a particular set of random numbers are generating repeatedly. Can anybody mention the correction here???
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
main()
{
int i,a[40];
for(i=0;i<40;i++)
{
a[i] = rand() % 6;
printf("%d\n", a[i]);
}
getch();
}
You need to initialize random seed to a different value, please see http://www.cplusplus.com/reference/cstdlib/rand/
Per the documentation,
If rand() is called before any calls to srand() are made, the same sequence shall
be generated as when srand() is first called with a seed value of 1. [emph. mine]
You need to mix it up, something like this:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include <time.h>
main()
{
int i,a[40];
// seed the PRNG with some random value
// the current time is often used. You might want to incorporate
// other sources of entropy as well.
srand(time(NULL));
for( i = 0 ; i < 40 ; i++ )
{
a[i] = rand() % 6;
printf("%d\n", a[i]);
}
getch();
}
One should note that
seed the PRNG just once at beginning of execution
The reason for incorporating more sources of entity, rather than just relying on the current system clock is that the system clock itself is not very random -- to invocations quite close to each other my result in similar sequences. Other good sources of entropy include:
hard disk statistics
network I/O
process activity
keystroke latency
mouse movements
etc.
Although looking at user interface components such as keystrokes and mouse movements won't buy you much in the way of entropy if your software is running, say, on a server, where the keyboard and mouse are likely to be idle for long periods of time.
Do something like this (inserted line) to seed the random number generator:
//...
int i,a[40];
srand(clock()); //inserted line
for(i=0;i<40;i++)
//...
The clock() function will provide a different seed value each clock tick, resulting in a new and different initialization to the rand() function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char** argv) {
srand(time(NULL));
int r = rand();
printf("%d\n", r);
return (EXIT_SUCCESS);
}
When I run this code snippet repeatedly in the space of a few seconds, I get an increasing series of number such as 213252683, 213975384, 214193875, 214445980. It looks to me like I'm just printing out the system time - that hypothesis seems to be confirmed when I add the line printf("%d\n", time(NULL)); to the code. What am I doing wrong? I'm running on Mac OS X 10.6.1 (Snow Leopard), but I'm only using Standard Library functions, so it shouldn't make a difference. Thanks!
Pseudorandom numbers are generated as a chaotic sequence derived from an initial seed. srand initializes the randomness by setting this seed. Apparently, the first random number in the sequence is the seed itself - which is the time() value you set.
This is the reason, why the right way to generate a random sequence is to call srand() only once at the beginning of the program, and then only call rand() (well, maybe until the sequence starts looping, which shouldn't happen too soon, but that depends on the generating function). Calling srand() too often will, as you have seen, deteriorate the randomness.
The random number generator differs widely, so this will be difficult to reproduce on other machines. It looks like the first number from your implementation is just the seed value. On mine, for example, the first number appears to be linearly related to the seed. Generally, you will call srand once in a program, and rand many times, and successive calls will get more random-looking results. If you want to avoid this problem, it would be reasonable to do:
srand(time(NULL));
rand();
int r = rand();
printf("%d\n", r);
The first rand call makes sure the seed doesn't get returned, and the next one should pick up something that appears more random. Note that if you run the program twice in a short enough time span (such that time(NULL) is the same in both runs) you will get exactly the same results. This is definitely to be expected - use a different seed value (pid + time might be a good start, or just a higher-resolution time) if this is a problem.
When I run this code snippet repeatedly in the space of a few seconds,
I get an increasing series of number such as 213252683, 213975384,
214193875, 214445980.
I cannot reproduce this. On my system (Debian Linux) I get numbers that are not ordered. Also, the results are not the same as what you get when you print time(NULL).
This is as it should be: You are seeding the random number generator with the current time (in seconds). Thus as long as the time (down to seconds) is the same, your program will print the same result.
What am I doing wrong?
Well, that depends on what you want. If you want random numbers for every run, you need a better source of randomness. You could try functions like gettimeofday, which have higher resolution (typically ms, I believe). Also, mix in other sources of randomness, like the ID of your process.
In most programs, the effect you see is no problem, because typically srand() is only called at the start, and then rand() returns a different number on every call.
If you want "secure" (i.e. unpredictable) random numbers, that's a whole other game. See e.g. Wikipedia for an overview.
In case it helps I generally use it that way:
int rand_between(int min, int max)
{
static int flag = 1;
FILE *urandom;
unsigned int seed;
if (flag)
{
flag = 0;
if (!(urandom = fopen ("/dev/urandom", "r")))
fprintf(stderr, "Cannot open /dev/urandom!\n");
fread(&seed, sizeof(seed), 1, urandom);
srand(seed);
}
return ((int)rand() % (max - min)) + min;
}
To get a random uppercase letter:
char letter = (char)rand_between('A', 'Z');
You should use random() instead of rand(). It is superior to rand() in every way, and it is also included in stdlib.
Try the following code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int r = random();
printf("%d\n", r);
return (EXIT_SUCCESS);
}
I use this function to create random numbers between 100000000 and 999999999
int irand(int start, int stop) {
double range = stop - start + 1;
return start + (int)(range * rand()/(RAND_MAX+1.0));
}
When I use it like this, it's properly working
while(1) {
DWORD dw = irand(100000000, 999999999);
printf("dynamic key: %d\n", dw);
Sleep(100);
}
But when I use this function without the while(1), I always get the same number.
What do I need to fix?
The random number generator must be seeded with some source of entropy for you to see different sequences each time, otherwise an initial seed value of 1 is used by the rand function. In your case, calling srand (time(NULL)); once before the irand function is first called should do the trick. You might find this question useful: why do i always get the same sequence of random numbers with rand() ?
Not a direct answer to your question, but something you should probably read if you're struggling with random numbers. This recent article by our very own Jon Skeet is a good intro to random numbers and the trubles one might run into: http://csharpindepth.com/Articles/Chapter12/Random.aspx
gcc 4.4.4 c89
I am using the code below. However, I keep getting the same number:
size_t i = 0;
for(i = 0; i < 3; i++) {
/* Initialize random number */
srand((unsigned int)time(NULL));
/* Added random number (simulate seconds) */
add((rand() % 30) + 1);
}
I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times.
Many thanks,
You're seeding inside the loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time.
You need to move your seed function outside the loop:
/* Initialize random number */
srand((unsigned int)time(NULL));
for(i = 0; i < 3; i++) {
/* Added random number (simulate seconds) */
add((rand() % 30) + 1);
}
You need to call srand just once, at the beginning of your program.
srand initializes the pseudo random number generator using time in seconds. If you initialize it with a particular number, you will always get the same sequence of numbers. That's why you usually want to initialize it at the beginning using the time (so that the seed is different each time you run the program) and then use only rand to generate numbers which seem random.
In your case the time does not change from iteration to iteration, as its resolution is just 1 second, so you are always getting the first number of the pseudo-random sequence, which is always the same.
You need to do srand((unsigned int)time(NULL)) only once before the loop.
It is completely possible that the 3 times 17 are still completely random.
There is an about 1 in 10 chance of getting two numbers the same when using a range of 1-30 and three picks. (this is due to the birthday problem )
Now, getting three the same results has still a propability of 1 in 900 using the same range.
you might want to read more background on the analysis page of random.org
Seed to the pseudo Random number generator should be called only once outside the loop. Using time as a seed is good thing.
However there is still a possiblity of getting the same random number.
I rather suggest also using gettimeofday() system call to retrieve the seed to be used to feed srand().
Something like
struct timeval tv;
...
gettimeofday(&tv, NULL);
srand(tv.tv_usec);
...
This approach can add more entropy in your pseudo number generation code.
IMHO of course
Ciao ciao
I know this question has been asked time and again. I need random numbers between 0-9. I am using the following code:
srand(time());
int r;
for (;;)
{
while(condition)
{
r = rand()%10;
// ...
// ...
}
}
Now I am getting the same sequence of numbers for each iteration of for loop. Can someone provide me the correct code?
PS - My compiler doesn't recognize arcrandom().
This problem stems from the fact that on some implementations the lower-order bits of rand() are not very random. Quoting from the man page:
"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."
You're probably calling this function within the second, and srand is going to get seeded with the same second. You should only call srand once at the beginning of main.
Many pseudorandom generators have an observable period. If you need a long period consider using the algorithm from Knuth 2.
It has a period of about 2^55, and is simple to implement.
RANARRAY
Remove all srand() calls from your code.
Add one, unique call right before the first statement in main().
int main(void) {
int foo = 42;
int bar = baz(42);
srand(time(0));
/* rest of your program */
return 0;
}
Your code doesn't compile -- for() is not valid C.
Are you sure that you are calling srand only once, at the start of the program and before any rand calls? Calling srand within the loop would explain this behavior.
srand(time(0));
r = rand() % (max+1);
//r will be a random number between 0 and max.
I can only think that you did not initialize correctly, or your redacted code is redacted wrongly.
Have you random()?
random() man page
I have made simple program:
int i;
for(i=0;i<40;i++)
printf("%d",rand()%10);
And geting 7938024839052273790239970398657627039991 - no repeating here.
How long is your sequence?
Depending on your requirements for statistical randomness you might find it better to ditch the psuedo random number generator and try an external source.
random.org and randomnumbers.info (amongst others) will provide truly random numbers for download, which libcurl should handle for you.
The only possible way you could be getting the exact same sequence of numbers is if there is a call to srand() somewhere in the code that you haven't shown us. It could be deep within a function call somewhere.
The proper way to fix this would be to find the extra call to srand and remove it. However this quick hack might get you started:
static int seed = time();
int r;
for (;;)
{
srand(seed++);
while(condition)
{
r = rand()%10;
// ...
// ...
}
}