Home > database >  Randomly Generate Even Split of 1s and 0s in Array
Randomly Generate Even Split of 1s and 0s in Array

Time:07-26

I have a simple array, 20 members long, that I read a single value from, one at a time.

The array currently looks like this for testing purposes:

int PhaseTesting1Array[20] = { 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0}; 

What I need to do is randomize each of the members so that each member is randomly a 1 or 0, and there is an equal amount of each (10 ones and 10 zeros) but I'm having a hard time figuring out how to do get an equal number of ones and zeros using rand which seems to be what I should use.

CodePudding user response:

You can use std::shuffle with a predefined vector with 10 ones and 10 zeros. The following code is slightly adapted from cppreference.com.

#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v = {1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0};
 
    std::random_device rd;
    std::mt19937 g(rd());
 
    std::shuffle(v.begin(), v.end(), g);
 
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
}

You could also use std::random_shuffe(I first, I last) without the random number distribution argument which uses rand internally, but this is deprecated and removed with C 17.

  • Related