# 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.

## 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 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.

1. 1
Rutin
25
2. 2
3. 3
4. 4
JoeJ
18
5. 5

• 14
• 14
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631757
• Total Posts
3002131
×