views:

264

answers:

2

I need to randomize an NSArray that I have loaded with quiz questions, but I need to keep the elements in a specific order.

A: 

NSArray is an immutable object, meaning you can't change the order of elements. I think i get what you are getting at though. Just write some functionality overtop of your datastructure to choose elements of this array at random. You will need to keep track of what elements have been accessed already so you don't re-select them.

You could also make a copy of your array using the subtype NSMutableArray. Once a question has been selected, remove it from this array (you can do this because the array is now mutable)

You use a C function for random numbers. See rand() and srand()

darren
A: 

If I understand the question correctly: you have an array of questions, you want to show a subset (of a presumably fixed size?) of them, but the subset needs to preserve the order as in the original array?

Let's say you have N questions and want to randomly pick M of them. You could create an array of elements [0 .. (N - 1)] that stores indices to the original array. You then could shuffle this array using the Knuth/Fisher-Yate's algorithm, sort the first M elements, and use those first M indices to do lookups into the original array.

jamesdlin