Advanced NSArray shuffle?

Discussion in 'iOS Programming' started by mfoley89, Jan 3, 2010.

  1. mfoley89 macrumors newbie

    Jan 3, 2010
    I need to randomize an NSArray that I have loaded with quiz questions. I have read other posts about randomizing NSArray, but I need to keep the elements in a specific order.

    The array format is as follows:
    @"Question1",@"ans1",@"ans2",@"ans3",@"ans4",@"correct answer",
    @"Question2",@"ans1",@"ans2",@"ans3",@"ans4",@"correct answer",
    and so on...

    I would like to shuffle the array while keeping all these sets of 6 (the question and answer choices) next to each other. Any suggestions would be greatly appreciated.

    Thank you.
  2. kainjow Moderator emeritus


    Jun 15, 2000
    So break the array into subarrays which can be shuffled (see objectsAtIndexes:) and then combine them back together again (see replaceObjectsAtIndexes:withObjects:).

    Or, use an actual class to represent your data instead of a huge array. For example you could have a Question class which has ivars to hold the question's text, its answers, and the correct answer. Then you could put all the questions into an array, and then within each Question class provide a shuffleAnswers method. This would be the OOP way to do it :)
  3. KoolStar macrumors demi-god


    Oct 16, 2006
    You can create a class as mentioned before, or you could look at using plist or dictionaries. A plist/dictionary is basically an array or arrays. Therefore you would just have to randomly pick with object("array") you want to display.

Share This Page