You’re given an array of size n, containing arbitrary boolean values.
What is the fastest way to return the index of a random TRUE value.
The algorithm should randomly return any one of the indices containing a TRUE.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Something like this:
So for 4 values for example you get the following probabilities for their indices:
EDIT: As Steve Jessop pointed out the floating point comparision will eventually lead to a very non uniform selection. Assuming
unit_randomis defined asrand() / RAND_MAXthe comparision can be changed to:This won’t give perfect distribution due to the discrete nature of
randbut it will be better.