Basically, I have a vector with 10 elements, and I need to create another vector with 6 non-repeating elements, taken randomly from the first vector. Kind of like a 6-combination. The thing is, though, that I cannot successfully exclude the repeating elements and I always get repeated elements in my 6-element vector.
I tried several things: nested loop with an iterator to check content of the vector, I tried removing the element, which I just inserted into the second element - I get crashes or repeated elements in the end.
What is the best approach? Something I haven't tried yet is using binary search.
Here are some attempts I did, which did not work. I do understand why they do not work, but not well enough to improve these solutions and make it work.
//One try - vec3 is a vector if integers
vector<int>::iterator iter;
srand(time(NULL));
vector<int> sixComb;
for(int i=0; i<6; i++)
{
int k=1+rand()%10;
int numb = vec3[k];
if (sixComb.size() == 0)
{
sixComb.push_back(numb);
}
for (iter=sixComb.begin(); iter != sixComb.end(); ++iter)
{
if (numb == *iter) break;
if (numb != *iter) sixComb.push_back(numb);
}
}
//Second try
vector<int>::iterator iter;
srand(time(NULL));
vector<int> sixComb;
for(int i=0; i<6; i++)
{
int k=1+rand()%10;
int numb = vec3[k];
do
{
sixComb.push_back(numb);
}
while (numb!=sixComb[i]);
}
//Three - I tried deleting the element I have just inserted
for(int i=0; i<6; i++)
{
int k=1+rand()%10;
int numb = vec3[k];
sixComb.push_back(numb);
vec3.erase (vec3.begin()+k);
}
The elements in my original vector are fixed and there are NO repeated elements in there.
The order does not matter, the resulting 6-element vector would eventually be sorted.
@Duoas how would that assure me that there will be no repeated elements in the new vector?
Edit: I think I understand - because of the fact that I just use the original vector's content once, without copying repeatedly differeny, random elements N times.