I wrote a piece of code that generates MAX_SIZE amount of numbers from 0 to 9 and stores them in a vector called random so that the same digit does not appear twice, with a maximum value of 10 digits. The code seems to work, but rarely (or when opening it repeatedly), it seems to stop working and locks until someone closes it. I guess this has something to do with the random number generation but I'm not sure, I'm still learning. This is the full code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;
vector<int> random;
constexpr int MAX_SIZE = 10; //can be up to 10, try and change it over the limit
int generate() { //generates a casual number between 0 and 9
int a = 0;
a = rand() % 10;
return a;
}
int rand_elem(int a) { //makes sure the arg "int a" is not already contained in the vector<int> random
for (unsigned o = 0; o<MAX_SIZE; ++o)
if (a==random[o]) {
return 1;
break; //returns 1 and interrupts the check if there is a match (aka if there is already that number in the vetcor<int> random
}
return 0; //else returns 0 aka success
}
void random_fill() { //"fills" vector<int> random with different random numbers from 0 to 9
for (unsigned i = 0; i<MAX_SIZE; ) {
int num = generate();
if (i==0 || rand_elem(num)==0) { //checks if the newly generated number with generate() doesn't already belong to vector<int> random
random.push_back(num);
++i; //if int num doesn't belong to vector<int> random, it is being added to it and the loop can proceed (++i) until the condition i<4 is met
}
}
}
int main()
try {
if (MAX_SIZE > 10) {
throw (runtime_error("MAX_SIZE too big\n"));
}
srand(time(NULL)); //generates a seed for the random number generator generate() using system time
random_fill();
for (unsigned h = 0; h<random.size(); ++h) //prints the content of the vector
cout<< random[h] << '\t';
} catch (runtime_error& e) { //error catching
cout <<"runtime error: "<< e.what()<<'\n';
return 1;
}
Hope this doesn't seem too redundant as a question but I haven't found any answer by searching on the site. Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire