Jump to content
  • Advertisement
Sign in to follow this  
guvidu

Random number from an array of values

This topic is 4076 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 its true? I dont want to do like this - i = rand()%7; if(array == 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!