Kedar - 8 months ago 47

C++ Question

I want to distribute a vector of 52 numbers evenly in other two vectors. Such that each respective vector will have 26 values taken randomly from a primary vector. i.e in this case it is storein

**code**

`vector<int>p1;`

vector<int>p2;

for(int i=0;i<=storein.size();i++) //storein has a size of 52

{

int a=rand()%storein.size()+1;

int b=rand()%storein.size()+1;

if(a!=0)

{

cout<<"First player draw"<<endl;

p1.push_back(a);

cout<<p1[i]<<endl;

}

if(b!=0)

{

cout<<"Second player draw"<<endl;

p2.push_back(b);

cout<<p2[i]<<endl;

}

}

cout<<"p1 "<<p1.size()<<" p2 "<<p2.size()<<endl;

Answer

You can just shuffle your input vector and then put the first 26 entries in `p1`

and the last in `p2`

:

```
std::mt19937 rd{std::random_device{}()};
std::shuffle(input_vec.begin(),input_vec.end(),rd);
std::vector<int> p1 {input_vec.begin(),input_vec.begin()+26};
std::vector<int> p2 {input_vec.begin()+26, input_vec.end()};
```

If you don't want to change `input_vec`

, just make a copy.

Note that this way of seeding the mt19937 is potentially not quite optimal as its state space is quite a bigger than the 32 bit seed. This won't matter for toy programs and your standard programming assignment, but for completeness sake: Here is my take on properly seeding the whole state space.

As a last remark: Do not use `rand()`

, it is bad.

Source (Stackoverflow)