Random Number Generator mechanism - c++

i had the following problem in my book:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
randomize();
int Game[]={10,16},P;
int Turn=random(2)+5;
for(int T=0;T<20;T++)
{
P=random(2);
cout<<Game[P]+Turn<<"#";
}
getch();
}
The output comes like 16#22#16#16#16#22#....20 times...
Why the output of this always comes either 16# or 22#?? why not 15# or 21#?? i would like to the mechanism of this program. Thanks.
turn=random(2)+5;
if random(2) gives 0 then turn becomes turn=0+5=5 which implies that i should get 10+5=15 and 16+5=21 along with 16 and 22 but i m not getting them.
We got the above question in our computer science theory exam and we were to chose the correct answer(i.e it generates 16 and 22) but how will i am going to know that it will generate only 16 and 22. As i explained above 15 and 21 are also possible..

maybe this helps:
The seed for the random number generator is not set.
If you call srand(time(NULL)) then you will get more random results
C++ rand() gives same number when running process

You need to give a seed value that would help get "really" random. mumbers

A computer cannot randomize numbers by itself, it uses a seed for that.
But seed's aren't completely random they just have a specific order, like:
1
2
8
5
4
These numbers look pretty random but when you run the program the next time you will get:
1
2
8
5
4
The exact same.
To prevent this we use the time as a seed, time always changes so it will always generate new numbers.
#include <time.h>
srand(time(NULL)); // srand is the function to randomize numbers from a seed, we use 'time' as seed here
this video explains it.

Because Turn is only randomized once - at the beginning of the loop. If you move the assignment of Turn into your loop, you should get 15 and 21 also:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
randomize();
int Game[]={10,16},P;
int Turn;
for(int T=0;T<20;T++)
{
P=random(2);
Turn=random(2)+5;
cout<<Game[P]+Turn<<"#";
}
getch();
}
Also, as said by others, if you want the output to differ between runs, you will need to seed your random number generator, for instance by calling srand() with a seed. For instance:
#include <time.h>
(...)
srand(time(NULL));

Related

Rand() command generates the same numbers every time [duplicate]

This question already has answers here:
C++ random number same sequence every time
(2 answers)
Random seed at runtime
(3 answers)
Closed 1 year ago.
I'm using rand() in a loop to generate random numbers every time till the loop is complete, but it always gives the same number, what am I doing wrong?
bool PlayGame(int Difficulty, bool bComplete)
{
int CodeA =rand() % Difficulty + Difficulty;
int CodeB =rand() % Difficulty + Difficulty;
int CodeC =rand() % Difficulty + Difficulty;
You can use current time as seed for random generator by setting srand(time(0)); at start
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Driver program
int main(void)
{
// This program will create different sequence of
// random numbers on every program run
// Use current time as seed for random generator
srand(time(0));
for(int i = 0; i<4; i++)
printf(" %d ", rand());
return 0;
}
Output 1:
453 1432 325 89
Output 2:
8976 21234 45 8975
Output n:
563 9873 12321 24132
Ref.
If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs.
The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1)
so, set srand(time(0)); at start of the program

Need to generate a unique 5 digit number from 00001 to 99999 in C++ [duplicate]

This question already has answers here:
Generate random numbers uniformly over an entire range
(20 answers)
rand() returns same values when called within a single function
(5 answers)
Closed 4 years ago.
We will modify part of the existing menu logic to generate an ID for the user. This user ID will be of the type int, and will be 5 digits in length. The values are 00001 – 99999, and should appear with all 5 digits (leading zeroes) on the display upon generating them. Do not change the data type from that of an int. Check out the setfill manipulator as a possible helper for this. Setfill allows you to set a fill character to a value using an input parameter, such as ‘0’ for leading zeroes. Researching it, you’ll see that you will need to reset the fill character after use too, or you will be printing a lot of zeroes on the display! Your program also should guarantee an absolutely unique user ID has been generated for each new activity that is added. Think about how this works...
Currently I've been trying to get the following code to work
srand(time(0));
cout << setfill('0') << setw(5) << rand() %99999 << endl;
Problem is that this doesn't seem random at all (it's just slowly counting up based on the computers internal clock right?) and the first digit is always zero. Like the instructions say it should be between 00001 and 99999.
EDIT: I appreciate the different solutions, but most of them are more advanced than what I'm supposed to be using for this assignment. I'm fairly sure srand() and rand() is what I should be using.
Okay, so it seems you must use the rand() function to generate a value between 1-99999. So with that in mind, the following code should generate random values in the required range:
#include <iomanip>
#include <iostream>
const int randID()
{
return 1 + (std::rand() % (99999));
}
int main()
{
for(int i = 0; i < 1000; ++i)
std::cout << std::setfill('0') << std::setw(5) << randID() << '\n';
return 0;
}
For me it prints, for example:
01886
21975
01072
11334
22868
26154
14296
32169
20826
09677
15630
28651
Which should satisfy your requirement of 0-padded values between 1-99999. Also, as mentioned in the comments. Do look into the <random> for your random number needs outside this assignment as it generates far superior random numbers, and offers way more generators, distributions and better seeding.

Data type to store more than 20 digits of value

‪#‎include‬ <iostream>
#include <conio.h>
using namespace std;
int main()
{
double n,m,a, count=0;
cin>>n>>m>>a;
double length=n;
while(m>0)
{
while(n>0)
{
count=count+1;
n=n-a;
}
m=m-a;
n=length;
}
cout<<count;
getch();
return 0;
}
sample input
6 6 4
output
4 (working fine)
sample input
1000000000 1000000000 13
output
___ no output
Means it is working fine with small range of "count" value. If value exceeds from its limit then it is not printing anything. I have tried all range of values. Please help me
The reason you are getting no output with the sample input of 1000000000 1000000000 13 is because it takes far too long.
The inner loop runs 76923077 times, and the outer loop runs 76923077 times. This means that the inner code count=count+1 is running 5.91 x 10^15 times. Even if the inner code could run in a picosecond (it can't), it would take more than 98 hours to complete.

Time Limit Exceeded - Simple Program - Divisibility Test

Input
The input begins with two positive integers n k (n, k<=10^7). The next n lines of input contain one positive integer ti, not greater than 10^9, each.
Output
Write a single integer to output, denoting how many integers ti are divisible by k.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
My Code:
#include <iostream>
using namespace std;
int main()
{
long long n,k, i;
cin>>n;
cin>>k;
int count=0;
for(i=0;i<n;i++)
{
int z;
cin>>z;
if(z%k == 0) count++;
}
cout<<count;
return 0;
}
Now this code produces the correct output. However, its not being accepted by CodeChef(http://www.codechef.com/problems/INTEST) for the following reason: Time Limit Exceeded. How can this be further optimized?
As said by caleb the problem is labeled "Enormous Input Test" so it requires you to use some better/faster I/O methods
just replacing cout with printf and cin with scanf will give you an AC but to improve your execution time you need to use some faster IO method for example reading character by character using getchar_unlocked() will give you a better execution time
so you can read the values by using a function like this , for a better execution time.
inline int read(){
char c=getchar_unlocked();
int n=0;
while(!(c>='0' && c<='9'))
c=getchar_unlocked();
while(c>='0' && c<='9'){
n=n*10 + (c-'0');
c=getchar_unlocked();
}
return n;
}
The linked problem contains the following description:
The purpose of this problem is to verify whether the method you are
using to read input data is sufficiently fast to handle problems
branded with the enormous Input/Output warning. You are expected to be
able to process at least 2.5MB of input data per second at runtime.
Considering that, reading values from input a few bytes at a time using iostreams isn't going to cut it. I googled around a bit and found a drop-in replacement for cin and cout described on CodeChef. Some other approaches you could try include using a memory-mapped file and using stdio.
It might also help to look for ways to optimize the calculation. For example, if ti < k, then you know that k is not a factor of ti. Depending on the magnitude of k and the distribution of ti values, that observation alone could save a lot of time.
Remember: the fact that your code is short doesn't mean that it's fast.

Random Boolean Value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to generate a random int that is either 0 or 1 in C++. Right now, I receive a 0 every time I run this code, and I'm not sure why. What's the problem here?
#include <ctime>
#include <cstdlib>
srand(time(0));
int randomval = rand() % 2;
cout << randomval << endl;
It is called bad luck. Try it again.
I know this is an older question but I believe this answers the question properly.
Don't re-seed the the generator every time you run that code.
By seeding it to the same value every time, you're just gonna get the same "random" number. Remember this is a Pseudo-Random number generator, so based on the seed value, a "random" number will be generated. So if you seed it with the same number every time you're just gonna get the same number every time.
The solution is to call srand(time(NULL)) only once in your program execution. Then, each call to rand() will give you a different number every time.
On theory, there's 50% chance you get 0, and 50 - 1. You may want to try with different modulo - for example 100, to check if this works. And I'm sure it does.
You have just ran this code a few times, not enough.
Other idea to test it:
srand(time(0));
for( int i = 0; i < 1000000; ++i )
{
assert( 0 == ( rand() % 2 ) );
}
I would like to add that when you use srand(time(0)); the "random number" will always be the same in the same second. When I tried to run your program 10000 times and group it by uniq I saw that the number would not change within a second.
for i in `seq 1 10000`; do ./a.out; done | uniq -c
693 0
3415 1
675 0
673 1
665 0
674 1
668 0
711 1
694 0
673 1
459 0
bool random() {
if (rand() % 2 == 0)
return true;
else return false;
}
Call srand(time(NULL)); just once.
Then use a loop like this, you will always get a 0 or 1 this way.
#include <stdio.h>
#include <stdlib.h>
srand(time(NULL));
for (i=0;i<10;i++)
{
printf("%d\n",rand() % 2);
i++;
}
return 0;
Although your code suggests that you want to receive them equally likely, you didn't state that, and perhaps you have simply thought that it was impossible to do otherwise. If you want a different distribution, and you are willing to rewrite your code (and make it C++11 compliant), you can do the following:
const double chance = 0.3; // this is the chance of getting true, between 0 and 1;
std::random_device rd;
std::mt19937 mt(rd());
std::bernoulli_distribution dist(chance);
bool result = dist(mt);
If you will need to do that in a loop, only repeat the last statement dist(mt), keep all the generated objects as they are without recreating them.
You are not checking against anything. Use:
#include <ctime>
#include <cstdlib>
srand(time(0));
int randomval = rand() % 2 == 0;
cout << randomval << endl;