mardi 27 février 2018

Generating random integers according to a Boolean slice in Go

I want to generate random integer values where indices in a Boolean slice is true in an efficient way. As an example consider the following Boolean slice:

BooleanSlice = [false, false, true, false, true]

This slice has two indices which have the true value, index 2 and index 4. The algorithm should then pick randomly between values 2 and 4. This should hold for any Boolean slice.

One solution would be to generate a random integer and then check if that value is true in the Boolean slice, picking a new value if false. However, that method seems very inefficient if the slice is large and there are only a few true values.

Is there anyway optimal way to generate random numbers following the above requirements?




Aucun commentaire:

Enregistrer un commentaire