Sign in to follow this  
guvidu

Random number from an array of values

Recommended Posts

Hello! Asume we have this array - array[7]={true,true,true,true,true,true,true}; after a while the array will become array[7]={false, true, true, false, true ,true, false}; How can i get a random number i that will return me one of the values that the array[i] its true? I dont want to do like this - i = rand()%7; if(array[i] == true) continue with the program else go back and chose another number; becouse what will it hapend when the array has all the members false; - crash So... can you tell me another way? Thank!

Share this post


Link to post
Share on other sites
Count the number of trues in the array, called N, and generate a random number n from 1 to N. Find the position of the n:th true, and select the corresponding value in the value array.

But if you have full control over the arrays, there may be better ways to select random values without repetitions. For example, in your value array, you could pick a random element and place it last. Next time, select a new random element among the N-1 first elements and place it second last. Basically, a random shuffle algorithm.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this