Q: Semi-random numbers generation in C++ Suppose I have a set of numbers x = {0, 0, 0, 0, 1, 2, 2, 3}. Is there a way for me to use rand() to print out random numbers from this list so that the proportion of the generated numbers over time actually would be the original proportion of the numbers in the set? In other words, so that the proportion of zeros would be about 0.5, ones would be 0.125, twos would be 0.25, and threes would be 0.125.

A: You can do it by specifying the frequencies:
#include <iostream>
#include <random>

int main()
{
    using namespace std;
    mt19937_64 engine;

    discrete_distribution<int> numbers{4, 1, 2, 1};

    cout << numbers(engine) << endl;
}


A: quick approach:
int values[8] = { 0, 0, 0, 0, 1, 2, 2, 3 };
int randomIndex = rand() % 8; // NOTE: feel free to replace with & 0x7
int randomValue = values[randomIndex];

NOTE: to provide uniform distribution number of values should be power of 2 (2,4,8,16,etc). If you need another number, you can use following:
int rand_range(int maxValue)
{
    int mask = 0;
    int tmp = maxValue;
    int r;

    while (tmp > 0)
    {
        mask = (mask << 1) | 1;
        tmp= (tmp>> 1);
    }

    r = rand() & mask;
    while (r > maxValue)
        r = rand() & mask;

    return r;
}

int values[XXXX] = { 0, 0, 0, 0, 1, 2, 2, 3, ... };
int randomIndex = rand_range(XXXX-1); // NOTE: -1 as maxValue is inclusive
int randomValue = values[randomIndex];

