My random number generator is printing duplicate numbers [duplicate] - c++

This question already has answers here:
Random number generator only generating one random number
(15 answers)
srand() — why call it only once?
(7 answers)
Closed 7 years ago.
I'm working on a program that uses a function that would generate 2 random integers that I would later use to ask the user to add and figure out the sum. For the time being, I came across a problem in which it's duplicating the same number.
Here's the program thus far:
#include<iostream>
#include<ctime>
using namespace std;
/*
This function generates a random integer
between 0 and max_int
*/
int get_rand_int(int max_int){
srand(time(0));
return int(rand()) % max_int;
}
This program generates random addition problems
with integers between 0 and 100
int main(){
int num1 = get_rand_int(101);
int num2 = get_rand_int(101);
cout << num1 << endl;
cout << num2 << endl;
Please note this this is a homework problem my teacher assigned. He provided us with the skeleton and we're trying to fill in the blanks. I have a feeling the problem lies within the srand section of my function but that was part of my teacher's work so I'm not sure whether I need to touch that. Thanks in advance.

Yes. srand initializes the random sequence with the result of time. However, time changes only once per second! This means that if you call your function twice in a one-second delay, you get the same number.
One solution is to call srand just once, at the beginning of your program (in the main function, for instance).

You must seed the random generator only once in your program,
srand(time(0)); // this must happen only once, at the beginning of main()
You now seed it inside the function get_rand_int, and call the function twice in a very short amount of time. The seed ends up being the same, so you get the same sequence of numbers.

Call the srand(time(0)) in the main to set the current time only once to use random generation instantly.
int main(){
srand(time(0));
int num1 = get_rand_int(101);
int num2 = get_rand_int(101);
cout << num1 << endl;
cout << num2 << endl;
}

Related

How to fix empty values when using rand and srand in a Merge Sort with C++?

I'm trying to create a program using Merge Sort for an assignment, using rand and srand to place random numbers in the array. The goal is to sort a large number of values entered manually by the user and count how long it takes the program in seconds to process it.
Everything works so far, but the one problem I'm getting is that a random value is only being assigned to the first position and the rest are given 0
This is the body of my merge function (main program) where I suspect the issue might be:
//Function that begins the Merge Sort option and acts as int main()
void mergeSortAlg(){
srand(time(NULL));
int n= 0;
cout << "\n\nPlease make a selection by typing one of the following:\n";
cout << "1000 \n10000 \n50000 \n\n";
cin >> n;
cout << "You have selected: " << n << "\n";
cout << "Stopwatch has started...\n\n";
//statement that begins counting the execution time for the program
auto start = chrono::steady_clock::now();
int arr[n]= {rand() % 100}; //generating random values between 1-99 in the array
int arr_size= sizeof(arr) / sizeof(arr[0]);
cout << "The array list before sorting is: \n";
displayMergeArray(arr, arr_size);
mergeSorting(arr, 0, arr_size-1);
cout << "\n\n\nThe array list after sorting is: \n";
displayMergeArray(arr, arr_size);
auto end = chrono::steady_clock::now(); //stopping the timer at the end of the merge sort
//printing the amount of time (in seconds) the program took to sort the values
cout << "\n\n\nTotal processing time elapsed:\n" << chrono::duration_cast<chrono::seconds>(end - start).count() << " seconds\n\n\n";
}
Note that the mergeSortAlg() function just acts as int main() since the main program currently is being used to call a menu function for 3 sorting options
Still kind of new to merging and C++ in general, so I'm not sure how to use rand to assign the number of random values needed based on how many positions are entered by the user.
You expect array initialization to work in a way it does not work. This
int arr[n]= {rand() % 100};
Initializes the first element with rand()%100 and the remaining elements are zero-initialized.
Moreover int arr[n] is not valid c++. See here: Why aren't variable-length arrays part of the C++ standard?.
You can use a std::vector when the size is only known at runtime and you can use a loop to roll n random numbers instead of just one:
std::vector<int> arr(n);
for (auto& e : arr) e = rand() % 100;
PS: Note that rand() is not the best way to generate random numbers. rand() is only loosely specificed and implementations are known to have issues. And on top of that rand() % N is not uniformly distributed (only if RAND_MAX % N == 0). You can find better random generators in <random>.

How do I "surpass" the int function of C++

Alright so, I'm a noob first of all. I started studying code (in C++), and I want to make a random number generator. It's great and all, but as far as I've observed, the generated numbers never exceed the "int" limit of 32768, even tho my variables are all "unsigned long long" (I'm pretty sure that's how you get the largest pool of numbers). I'm pretty sure it's something small, but it;s been bothering me for a day, and I really need answers.
Here's how my current code looks like :
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
unsigned long long n,m,r,mx;
cout<< "Please Enter The Number Of Desired Randomly Generated Numbers : ";
cin>>m;
cout<< "Please Enter An Upper Limit to the Random Numbers : " ;
cin>>mx;
srand ( time(NULL) );
for (int i=1; i<=m ; i++)
{
n = rand() % mx;
cout << n << endl;
}
cout<< "Rate this Program Out Of 10: ";
cin >> r;
cout << r << " " << "/" << "10";
return 0;
}
Even though all the numbers you use are unsigned long long, rand() will only ever return a number less than or equal to RAND_MAX which is guaranteed to be 32767 or more.
To guarantee a return value more than 32767 you're going to need some more advanced random number generation techniques. The standard library has a module for this called random.
Take a look at the uniform_int_distribution object. That page gives an example of how to use it to generate regular integers however the object does take a template parameter that allows you to specify what kind of integer is returned.
In your case you would want to use:
std::uniform_int_distribution<unsigned long long>
Using that in the example on the page will generate 10 unsigned long long numbers (however if you copy the example exactly they will still be limited to between 1 and 6).

C++ Random numbers 0 - 16 [duplicate]

This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Randomly shuffle C++ array (different each time)
(1 answer)
Closed 8 years ago.
Im working on a hangman game for class, i'm having trouble getting a random number.
Everytime I run the code I get the same number. Not sure what the problem is here, anything would help.
string pickWord(){
int random = rand() % 17;
string word = ::wordList[random];
cout << word << endl;
return word;
}
You have to seed random with time, otherwise it will always be the same.
take a look at this:
http://www.cplusplus.com/reference/cstdlib/srand/
your code should look like this
string pickWord(){
srand (time(NULL));
int random = rand() % 17;
string word = ::wordList[random];
cout << word << endl;
return word;
}
and also you have to add an include
#include <time.h>
This way, random will be dependant on the time, it is run, not on the compilation time.

Generate random number between 1 and 9 in c++

What do I need to add, so that it will not continuously choose the number as 8 but rather any of the numbers 1 through 9? srand?
int main()
{
int iRand = (rand() % 9+1);
if (iRand==1)
{
cout << "The planet of the day is Mercury!" <<endl;
cout << "Mercury is the closest planet to the sun." <<endl;
}
else if (iRand==2)
{
cout << "The planet of the day is Venus!" <<endl;
cout << "Venus is the hottest planet in our solar system." <<endl;
}
// .... 3..4..5..6..7..8
else
{
cout << "The planet of the day is Pluto!" <<endl;
}
return 0;
}
You need to initialize your random seed first!
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
srand (time(NULL));
Pseudorandom number generators like rand() aren't actually totally random. Instead, the numbers are determined by the generator's initial state, called a seed. Your program, as it exists now, will have the same seed on every execution--and thus the random number will be the same every time.
srand() to the rescue -- it lets you specify the seed.
If you were to specify a constant seed (like srand(2)) then you'd have the same problem as now, just with a different result. Thus, to guarantee differing results every time the program executes, we can initialize the random number generator with the current time -- so as long as you never travel in time, you'll never get the exact same sequence of numbers.
(Note: in a real world applications, this might not be good, because someone could repeat past results by (e.g.) manually resetting the system clock to different times. Which someone did once to steal money from a casino.)

Mysterious random number - wanting to be the same even after "srand()" [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Rand generating same numbers
The following is tried when answering another question on StackOverflow:
#include <time.h>
#include <iostream>
using namespace std;
main() {
srand ( time(NULL) );
cout << (float) rand() / RAND_MAX << endl;
cout << ((float) rand()) << endl;
cout << RAND_MAX << endl;
cout << (float) rand() / RAND_MAX << endl;
}
Very strangely, the first output number is always a similar number, either on Windows 7 with cygwin or on Mac with Leopard.
The last number is a good random number from 0 to 1. If the first cout line is commented out, the first printed random number is always a similar value one.
How could that be happening?
I have stumbled upon this phenomenon myself in the past. The first call to rand() in four sequential runs of a test program gave the following output:
27592
27595
27598
27602
Notice how similar those numbers are? This is because the random number generator is initialized with the current time, and the first result is heavily influenced by that. Similar initial values for srand yield similar initial results for rand. It's as simple as that.
This similarity is irrelevant if you calculate rand() % n, but if you go with the rand() / m approach, this is a problem. For example, if you divide rand() by 100, you will get the same number 3 times in a row!
Now let's take a look at the second result of rand() in four sequential runs:
11520
22268
248
10997
This looks much better, doesn't it? A simple quick-fix is to call rand() a few times after seeding and simply ignoring the result.
int main()
{
srand(time(0));
rand(); rand(); rand();
std::cout << rand() / float(RAND_MAX) << std::endl;
}
rand() function in VS2008 returns this: return ((current_value = current_value * 214013 + 2531011) >> 16) & 0x7fff;. This current_value you set with srand. This function is such that it will return similar pseudo random numbers for similar seeds, and there is no help about it. The problem is that those bits that are the most random in first call are eaten up with >> 16 part. To workaround the problem just roll it a few times (rand(); rand();).