C++ random function return same numbers [duplicate] - c++

This question already has answers here:
Why do I get the same result with rand() every time I compile and run? [duplicate]
(4 answers)
rand() returns same values when called within a single function
(5 answers)
rand() generating the same number [duplicate]
(3 answers)
Closed 10 years ago.
I'm trying to get random numbers on range from 0 to 3. Using such code:
#include <cstdlib>
int index = rand() % 3;
But always getting the same results: 1 1 0 1.
What I'm doing wrong? Always the same numbers. Results should change their values after each compilation or during runtime?

Your forgot to ad
#include <ctime>
srand(time(NULL))
at the start of your program.
This will generate a new seed everytime you run your program based on the current time.

Results should change their values after each compilation or during runtime?
Actually, no, the results are supposed to be the same for a given seed, and if you do not set the seed explicitly with srand(), then the results will be the same each time you run. To get different results each time, you should set the seed using something derived from something not completely deterministic, like the time (not deterministic in the sense that you don't know the exact time at the moment it gets used to set the seed).

Related

Rand() isn't displaying random number, please help me understand what's wrong :) [duplicate]

This question already has answers here:
Why does rand() yield the same sequence of numbers on every run?
(7 answers)
Closed 3 years ago.
So I am new to C++ and learning all alone... until now everything went fine, but i am learning how to use rand() and the result does bother me a little...
So my goal is to generate a random number for the HP of a player at the beginning of a game. To be fair, I set up a minimal HP of 50 points and I want to create a random number with 50 being the minimal and 200 the maximum.
int HP = 50 + rand() %200;
cout << HP;
Now, the problem is:
The program always give me the same int.
To check the result i created a new project and only displayed the rand() number with the same values, and I got the same result -> 91.
this mean, I would say int HP = 91; would be exactly the same.
Practice and trial being the key to learn (I think) I tried the same rand() values on 5 new projects, always the same number...
std::srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).
Each time rand() is seeded with srand(), it must produce the same sequence of values on successive calls.
https://en.cppreference.com/w/cpp/numeric/random/rand
Therefore, what you're seeing is (awkardly) exactly what rand is supposed to do. The easy fix is to call std::srand(std::time(nullptr)); so that each time the program runs, it starts with a different seed.
The more advanced fix is to study The awesome C++ standard randum number library
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(50, 250);
int HP = uniform_dist(e1);
rand() isn't really the best random number generator, but if you're going to use it you need to seed it with the srand function as follows:
srand(time(0));

change random seed in program c++ [duplicate]

This question already has answers here:
Random seed at runtime
(3 answers)
Closed 7 years ago.
In my program, I have a function return_random_vector() which takes a set of numbers, say 1,2,3,4,5, and returns a random rearrangement of the numbers such as 2,5,1,4,3.
In order to do this, I set the seed srand(time(NULL)). For my program, I want to be able to call this function again with 1,2,3,4,5 and get another rearrangement of them, for example 3,1,4,5,2.
Is there a way I can set srand() so that the seed can be reset?
To get a different set, you can call return_random_vector() again without calling srand() in between.
Calling srand((unsigned)time(NULL)) right after the first call to return_random_vector() will likely generate the same set because time() will probably return the same value, which is the elapsed time in seconds.
So you would in fact be resetting the seed to the same value as it was before the first call. And setting the seed to the same value will generate the same set of random numbers again.
You could also take a look at std::shuffle (C++11).
Every time you call srand() with a different value, you initialize the random number generator to return a different sequence of values.
Just call srand() again in the same way. Since the time value will likely be different, you will get a different sequence of results from rand().
If it is possible you need to do this before the time() value has changed, you can use:
srand(time(NULL)+rand());
It's a while since I last wrote C++, so I'm not sure if you'll need to cast one or the other values before doing the addition, being that they're an int and a time_t.
For *nix system, you can try this one
unsigned seed;
read(open("/dev/urandom", O_RDONLY), &seed, sizeof(seed));
srand(seed);
For Windows, RtlGenRandom will give you an array of random bytes, which can be used as seed. Or just be used as a pseudo-random number.

What is a seed in terms of generating a random number? [duplicate]

This question already has answers here:
What does 'seeding' mean?
(4 answers)
Closed 6 years ago.
What is a seed in terms of generating a random number?
I need to generate hundreds to thousands of random numbers, I have read a lot about using a "seed". What is a seed? Is a seed where the random numbers start from? For example if I set my seed to be 5 will it generate numbers from 5 to whatever my limit is? So it will never give me 3 for example.
I am using C++, so if you provide any examples it'd be nice if it was in C++.
Thanks!
What is normally called a random number sequence in reality is a "pseudo-random" number sequence because the values are computed using a deterministic algorithm and probability plays no real role.
The "seed" is a starting point for the sequence and the guarantee is that if you start from the same seed you will get the same sequence of numbers. This is very useful for example for debugging (when you are looking for an error in a program you need to be able to reproduce the problem and study it, a non-deterministic program would be much harder to debug because every run would be different).
If you need just a random sequence of numbers and don't need to reproduce it then simply use current time as seed... for example with:
srand(time(NULL));
So, let's put it this way:
if you and your friend set the seed equals to the same number, by then you and your friend will get the same random numbers. So, if all of us write this simple program:
#include<iostream>
using namespace std;
void main () {
srand(0);
for (int i=0; i<3; i++){
int x = rand()%11; //range between 0 and 10
cout<<x<<endl;
}
}
We all will get the same random numbers which are (5, 8, 8).
And if you want to get different number each time, you can use srand(time())

c++ random numbers srand [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
rand function returns same values when called within a single function c++
I have a program which creates a new set of random numbers each mouse click. If I run the program without srand ( time(NULL) ); the numbers are the same each time. If I run the program WITH srand ( time(NULL) ); then it's possible for me to spam click and the numbers will repeat themselves. How can I get around this?
Your problem is about seeding the random number generator with the same value. The srand function is for initializing the so called "seed" for it. A seed can be used to generate the same random numbers in a sequence.
First you need to initialize the generator then just call the rand function without arguments, and it will generate random numbers. For example:
/* initialize random seed with actual date-time */
std::srand(std::time(NULL));
/* generate ten random number lower than 10 */
int random, times = 10;
while(times){
random = std::rand() % 10;
times--;
}
About the "spam click": std::time(NULL) has precision in seconds, so you're initializing the random seed with the same value if you click within the same second.
Here is an example on the official c++ reference site,
and another example on cplusplus.com too.
rand function is not very good at generating random numbers, take a look at boost::random. it is awesome and can create random and semi random numbers

C++ Simple 0-10 multiplication flashcard using rand()

I am having trouble grasping the concept of rand() and srand() in c++. I need to create a program that displays two random numbers, have the user enter a response, then match the response with a message and do this for 5 times.
My question is how do I use it, the instructions say I can't use the time() function and that seems to be in every tutorial online about rand().
this is what I have so far.
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int seed;
int response;
srand(1969);
seed=(rand()%10+1);
cout<<seed<<" * "<<seed<<" = ";
cin>>response;
cout<<response;
if(response==seed*seed)
cout<<"Correct!. you have correctly answered 1 out of 1."<<endl;
else
cout<<"Wrong!. You have correctly answered 0 out of 1."<<endl;
This just outputs something like 6*6 or 7*7, I thought the seed variable would be not necessary different but not the same all the time?
This is what the output should look like:
3 * 5 =
34
Wrongo. You have correctly answered 0 out of 1.
8 * 1 =
23
Wrongo. You have correctly answered 0 out of 2.
7 * 1 =
7
Correct! You have correctly answered 1 out of 3.
2 * 0 =
2
Wrongo. You have correctly answered 1 out of 4.
8 * 1 =
8
Correct! You have correctly answered 2 out of 5.
Final Results: You have correctly answered 2 out of 5 for a 40% average.
and these are the requirements:
Your program should use rand() to generate pseudo-random numbers as needed. You may use srand() to initialize the random number generator, but please do not use any 'automatic' initializer (such as the time() function), as those are likely to be platform dependent. Your program should not use any loops.
By the way, since this is C++, you should really seek to use std::uniform_int_distribution, e.g.
#include <functional>
#include <random>
...
auto rand = std::bind(std::uniform_int_distribution<unsigned>(0, 10),
std::default_random_engine());
Now, you can just use rand() to generate a number in the desired interval.
The way you are using it now seems fine. The reason why all the tutorials use time() is because the numbers will be different every time you run your program. So, if you use a fixed number, every time your program runs, the output (number generation) will be the same. However, according to your requirements this doesn't seem to be a problem (if you need the random generation to be different every time you run your program, please specify that in your question).
However, rand()%10+1 is a range from 1 to 10 and not 0 to 10 like you want.
AFTER EDITS
To get the desired output, all you need is to make two seeds like so:
seed1=(rand()%11);
seed2=(rand()%11);
cout<<seed1<<" * "<<seed2<<" = ";
Also, you can ask the user for a seed and then pass that to srand to make each run more random.
About the requirements:
please do not use any 'automatic' initializer (such as the time()
function), as those are likely to be platform dependent
std::time is a standard C++ function in the <ctime> header. I do not understand why it matters if the result is platform dependent.
Your program should not use any loops.
This is also a very strange requirement. Loops are fundamental building blocks of any program. The requirements seem very strange to me, I would ask your professor or teacher for clarification.
On windows you can use GetTickCount() instead if time().
You could use rand_s which doesn't need to be seeded.
On *nix systems you can utilize /dev/random.
(How to use /dev/random)
You use srand() to seed the random function. This is necessary otherwise you'd get the same sequence of number with each run, and each call to rand()
You can seed rand with whatever you please. You'll find most tutorials use the current time as a seed as the number returned is usually different with each run of the program.
If you truly can't use the time() functionality, I would pass the seed as a command line argument.
int main(int argc, char* argv[])
{
srand(atoi(argv[1])); // Seed with command line argument.
}