I have two functions here. One of them, get_spectro(), generates a random number between 12-37 to represent a fake number of elements. display_spectro() uses the number generated by get_spectro() to find the number of each of the different elements found. For example, if get_spectro() randomly generates a 12, that means that 12 difference elements were found. display_spectro() then generates a random number 12 times to simulate the 12 difference elements. The problem is I need the 12 elements to be different.
I cant seem to figure out why my code below is not giving me mutually exclusive elements. I thought the combo of a for and while loop I have under display_spectro() would ensure that there were no repeats, but after running it a couple times I still get the same number twice once in a while.
int rover::get_spectro()
//Simulates finding between 12-37 different elements in the core samples
{
srand(time(0));
int num_elements;
num_elements = 12 + rand() % 25;
return num_elements;
}
void rover::display_spectro()
//Generates a random number for each element type in the core sample
//between 1-109. This number represents one of the first 109 elements
{
vector<int> element;
int num_elements = rover::get_spectro();
int elem_num;
for(int count =0; count < num_elements; count++)
{
elem_num = 1 + rand() % 109;
element.push_back(elem_num);
for(int num =0; num < element.size()-1; num++)
{
while(elem_num == element[num])
{
elem_num = 1 + rand() % 109;
element.pop_back();
element.push_back(elem_num);
}
}
}
cout << endl;
for(int count =0; count<element.size(); count++)
cout << element[count] << endl;
}
But the last element is what I am making sure isnt a copy. If the last element is a copy of another element then I pop_back() to remove it and then push_back() a replacement, doesn't that make sense?