I am using the rand() function in my iPhone project to generate a random array index. I generate several random indexes and then get the objects from those indexes. However I don’t want to get one object more than once so is there a way to say generate a random number within the range of the array count (which I am already doing) excluding previously picked numbers.
i.e. something like this:
int one = rand() % arrayCount
int two = rand() % arrayCount != one
Thanks
Three possibilities:
Shuffling
Shuffle your array and extract the elements in their order.
Remember
Extract a random element and store it into a
NSSet. If you extract one the next time check if it’s already in the set. (This is linear time.)Delete
Use a
NSMutableArrayand remove already extracted elements from the array. If you don’t want to modify the original one make a mutable copy.Which one’s the best depends on your needs.