C++ random int function - c++

Hello dear members of stackoverflow I've recently started learning C++, today I wrote a little game but my random function doesn't work properly. When I call my random function more than once it doesn't re-generate a number instead, it prints the same number over and over again. How can I solve this problem without using for loop?
Thanks
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int rolld6();
int main()
{
cout<<rolld6()<<endl;
cout<<rolld6()<<endl;
system("PAUSE");
return 0;
}
int rolld6()
{
srand(time(NULL));
return rand() % 6 + 1;;
}

srand(time(NULL)); should usually be done once at the start of main() and never again.
The way you have it will give you the same number every time you call rolld6 in the same second, which could be a lot of times and, in your sample, is near guaranteed since you call it twice in quick succession.
Try this:
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdlib.h>
int rolld6 (void) {
return rand() % 6 + 1;
}
int main (void) {
srand (time (NULL));
std::cout << rolld6() << std::endl;
std::cout << rolld6() << std::endl;
system ("PAUSE");
return 0;
}
One other thing to keep in mind is if you run this program itself twice in quick succession. If the time hasn't changed, you'll get the same two numbers in both runs. That's only usually a problem when you have a script running the program multiple times and the program itself is short lived.
For example, if you took out your system() call and had a cmd.exe script which called it thrice, you might see something like:
1
5
1
5
1
5
It's not something you usually do but it should be kept in mind on the off chance that the scenario pops up.

You are constantly reseeding the random number generator. Only call srand(time(NULL)); once at the beginning of your program.

Random functions (no matter the language) are only partially random.
in every technology you will have a equivalent to
srand(time(NULL));
This piece of codes seeds the random function to a start value and then the numbers a generated from there onwards
this means if your always reseeding form the same value you'll always get the same numbers
In your case you want to do something like this (calling srand(time(NULL)); only once).
int rolld6 (void) {
return rand() % 6 + 1;;
}
int main (void) {
srand (time (NULL));
...
//call your function here
}
one of the advantage of seeding with the same value is to offer the possibility to regenerate the same sequence of random numbers.
in one of my games, I would randomly place objects on the screen, but I also wanted to implement a retry option. this options of reseeding from the same value allows me to redo it without storing all the random values ^^

Related

C++ Password Generator Generates Same Password [duplicate]

In this rather basic C++ code snippet involving random number generation:
include <iostream>
using namespace std;
int main() {
cout << (rand() % 100);
return 0;
}
Why am I always getting an output of 41? I'm trying to get it to output some random number between 0 and 100. Maybe I'm not understanding something about how the rand function works?
You need to change the seed.
int main() {
srand(time(NULL));
cout << (rand() % 101);
return 0;
}
This srand thing also works for C.
See also:
http://xkcd.com/221/
For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.
rand() % 101
in addition to calling srand() as mentioned by others.
srand() seeds the random number generator. Without a seed, the generator is unable to generate the numbers you are looking for. As long as one's need for random numbers is not security-critical (e.g. any sort of cryptography), common practice is to use the system time as a seed by using the time() function from the <ctime> library as such: srand(time(0)). This will seed the random number generator with the system time expressed as a Unix timestamp (i.e. the number of seconds since the date 1/1/1970). You can then use rand() to generate a pseudo-random number.
Here is a quote from a duplicate question:
The reason is that a random number generated from the rand() function isn't
actually random. It simply is a transformation. Wikipedia gives a better
explanation of the meaning of pseudorandom number generator: deterministic
random bit generator. Every time you call rand() it takes the seed and/or the
last random number(s) generated (the C standard doesn't specify the algorithm
used, though C++11 has facilities for specifying some popular algorithms), runs
a mathematical operation on those numbers, and returns the result. So if the
seed state is the same each time (as it is if you don't call srand with a truly
random number), then you will always get the same 'random' numbers out.
If you want to know more, you can read the following:
http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/
http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/
You are not seeding the number.
Use This:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
cout << (rand() % 100) << endl;
return 0;
}
You only need to seed it once though. Basically don't seed it every random number.
random functions like borland complier
using namespace std;
int sys_random(int min, int max) {
return (rand() % (max - min+1) + min);
}
void sys_randomize() {
srand(time(0));
}
"srand(time(NULL));" as 1st line at "main()" won't help you if you're using "rand()" at static init. somewhere. You better create "struct rnd_init { rnd_init() { srand (time (nullptr)); } }" named whatever suits you, as a static var at the scope where "rand()" is being used: at some constructor, or whatever.

Why use "time" in srand?

I like to learn by screwing around with code, recently I copied and pasted a random number generator code. Then I removed all the lines of code that were not "necessary" to make the executable work to generate a random number. The final straw was me deleting "time" from srand.
srand((unsigned) time(0));
What is the point of "time(0)" here?
Does it use the time that the program is opened to generate the seed for the random number? Is that why removing it (time) makes it not work? Because then it doesn't have a seed?
Also...
include <stdlib.h>
include <stdio.h>
include <time.h>
int main()
{
srand((unsigned) time(0));
printf("Your dice has been rolled! You got:");
int result = 1 + (rand() % 20);
printf("%d", result);
}
that's the whole code and I noticed it used the "rand" result for output. Does the "rand" pull the seed from "srand"?
If you don’t “seed” the random number generator (or if you use the same seed value), you’ll get the same set of pseudorandom numbers.
Using the current time is an easy way to get a different seed every time.
The effect of srand cannot cross threads, so the random number seed should be set once on each thread. #Buddy said that using time(0) is the most convenient way to do this, and each call will get a different seed.Of course you can use an atomic variable .
std::atomic<int> seek(2374213); //init whatever you like
void thread1fun()
{
srand(++seek);
//...
int rand_num = rand();
}
void thread2fun()
{
srand(++seek);
//...
int rand_num = rand();
}

Clarification on calling srand [duplicate]

This question already has answers here:
How often should I call srand() in a C++ application?
(4 answers)
What does 'seeding' mean?
(4 answers)
Closed 3 years ago.
I'm wondering why it's advantageous to seed srand at the beginning of the program, instead of where I use it.
I generate pseudo-random numbers when seeding srand at the beginning of my program but I get the numbers all the same when I seed srand inside the function I call to generate the numbers
#include <iostream>
#include <ctime>
using namespace std;
int rng()
{
const int SIZE = 10;
int rng[10];
srand(time(NULL));
for (int i = 0; i < 10; i++)
{
rng[i] = rand() % 128 + 1;
return rng[i];
}
}
int main()
{
int array;
//srand(time(NULL)); If i put it here i get actual random numbers
cout << "Welcome to the program";
cout << "\nthis is your rng\n";
for (int i = 0; i < 10; i++)
{
array = rng();
cout << array << endl;
}
return 0;
}
When I run the program all of the numbers are the same, but when I delete the seeding from in the rng function and uncomment the srand in the main module the numbers are pseudo-random which is what I want. Im wondering why though. I've looked into it and heard that im seeding srand with a time and when I run that function the loop iterates so fast that all of the numbers are generated with the same seed value so they're all the same, but I'm wondering what's the difference from that and having srand(time(NULL)) in main because either way doesn't the function generate the numbers so fast they'll be at the same seed value anyway? It doesn't appear that way because of the different output but im curious, why?
time returns number of seconds since 1.1.1970 so calling it repeatedly during one second will indeed return same values. It doesn't matter exactly where you put srand as long as it's before all rand calls and it should only be called once per program as it's global and obviously resets the random sequence. So if you use it only where you need it, you risk that when some other part of the code will need it too and calls srand again, it will interfere with your rand calls. It's not necessary to call it at all but then the seed will always be the same. It's good for debugging to have an option to set the seed deterministicly.
That said, don't use it, just don't.
As you observed time is not a good seed generator and rand is not even good random number generator, certainly not for floats and x mod n. Use <random> library. It has std::random_device which can generate true random numbers = good seeds. Sadly it's not required to. std::mt19937 is go-to RNG which together with std::XX_YY_distributions should be more than enough for everything but the most extreme need for randomness. It's also thread-safe because you control access to the generator and how it's used.

Autoclicker using C++ to click in differnent intervals using RNG * Milliseconds to determine the time between clicks

I've been testing it for hours now and I just can't get it to work.
I'm trying to get an Autoclicker to work, using C++.
Said Program should be able to click without moving the mouse, not specified in the Programm.
The mouse only needs to left-click.
This has to be done in different intervals. My idea was, that we use a Random Number Generator (RNG) to determine a Number between 1 and 100.
This step is easy just using a (rand() % 6) + 1 command.
Loading the library you can use the command srand(time(0)) before the for function to actually randomize it.
My problem lies after that.
How to I get the resulting random number to be multiplied by Milliseconds (preferably also randomized) and then use the resulting time as the time beween mouse outputs?
I know this is much to ask but I'm pretty new to coding and this is a passion project. If anyone would be experienced enough to help me out with my problem it would be greatly appreciated.
Edit: This is what I have so far, I know it's not much but it works. Improvements are obviously welcome though.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
/* function main begins program execution */
int main(void) {
int i;
srand(time(0));
for (i = 1; i < 2; i++) {
printf("%d ", 1 + (rand() % 6));
}
cin.get();
return 0;
}

Need help soccer simulation

I need help with a winning condition and randomly placing teams against each other...i randomly selecting teams to play and i keep getting the same teams playing twice or playing itself and idk what to do
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <cmath>
#include <stdlib.h>
#include <sstream>
using namespace std;
struct teams{//declaring a struct for the teams
string side;
int number;
int number1;
}teams1[16], points[16];
//void intro screen(){//function for the introduction screen
void fileData(){//function for reading the teams data file
ifstream input;
input.open("FootballTeam.txt",ios::in); //associate file
if(input.is_open()){//opening the file
for(int x=0; x<16; x++){//looping through the file
input>>teams1[x].side;//getting info from the file
cout<<teams1[x].side<<endl;//printing out the data from the file
}//end for
}//end if
}//end void
void play(){//function for playing the game
srand(time(NULL));
for(int x=0; x<=1; x++){//loop for random teams to play
for(int s=0; s<=7; s++){//loop for randoms goals value
x=rand() %16+1;//randomly selecting two teams
points[s].number=rand()%4+1;//randomly selecting goals
points[s].number1=rand()%7+3;//randomly selecting goals
cout<<teams1[x].side<<" :"<<points[s].number<<" vs "
<<teams1[s].side<<" :"<<points[s].number1<<endl<<endl;//printing out the teams and goals
//cout<<teams1<<" Won this match"<<endl;
}//end for
}//end for
}//end void
int main (){
cout<<"ROUND OF 16 Finalists!!!\n"<<endl;
fileData();
cout<<"\n";
system("PAUSE");
system("CLS");
play();
return 0;
}//end main
The rand() pseudo-random number generator uses its default seed if you don't call srand() before using rand(). To prevent rand() from using the default seed on every run of your program, and thereby always choosing the same pairs of teams, you should call srand() and pass in time(NULL), which I see you have done. Since your program will never run at the same time twice, rand() will output different numbers on each run.
However, note that you should only call srand() once. So you need to call it in main(), as soon as your program starts up. Right now you're calling srand() every time play() is invoked. The time intervals between each invocation of play() are probably very small. Thus, rand() ends up being seeded with virtually the same number every time, since the time differences are too small. This effectively starts rand() at the same point in its pseudo-random number sequence, which is why you see the same teams playing each other.
int main() {
srand(time(NULL));
// now you're free to use rand() for the rest of the program
// ...
}
See this reference for more information on srand().