I am new to c++. I am trying to generate 4 random unique numbers from 0 to 9. Here is my code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> vect;
int randNums = 4;
int countSameNums = 0;
int randNumber;
srand(time(0)); // Initialize random number generator by setting the seed
// generate 4 random unique integers and insert them all into a vector
while (true){
randNumber = rand()%10;
for (int i = 0; i < vect.size(); i++){
if (randNumber == vect[i]){
countSameNums += 1;
}
}
if (countSameNums == 0){
vect.push_back(randNumber);
countSameNums = 0;
}
if (vect.size() == randNums)
break;
}
for (int el : vect){ // print out the content of the vector
cout << el <<endl;
}
}
I can compile the code without problems. However when I run it, sometimes it prints out the correct result, i.e. the 4 unique integers, but other times the program just hangs. I also notice that If I comment the line srand(time(0))
(my random seed) it prints 4 unique numbers every time, i.e. the program never hangs. The problem of course is that by commenting srand(time(0))
I get always the same sequence of unique numbers and I want a different sequence every run. Any idea on why this isn't working? thanks