Something like that:
int count = 0;
int index = -1;
for (int i = 0; i != n; ++i)
{
if (values[i])
{
++count;
if (unit_random <= 1.0f / count)
{
index = i;
}
}
}
So, for 4 values, for example, you get the following probabilities for your indices:
1: (1 / 1) * (1 / 2) * (2 / 3) * (3 / 4) = 1 / 4
2: (1 / 2) * (2 / 3) * (3 / 4) = 1 / 4
3: (1 / 3) * (3 / 4) = 1 / 4
4: 1 / 4 = 1 / 4
The EDIT: . Steve Jessop noted that floating-point comparisons will ultimately lead to very uneven choices. Assuming what unit_randomis defined as rand() / RAND_MAX, the comparison can be changed to:
typedef unsigned long long u64;
u64 product = u64(count) * rand();
if (product <= u64(RAND_MAX))
- rand, .