Question

I'm trying to create a memory game and I'm stuck with no idea how to randomly populate my cells with pictures from an array. I've just started out Xcode programming mainly for the iOS and I have searched for days on Stack Overflow but I can't seem to find an answer. Either that or I don't really understand what you professionals have said and explained.

Could anyone kindly please enlighten me?

Was it helpful?

Solution

This code will take an NSArray containing the pictures and produce a new array containing the pictures in random order. Then, you can save the new array and use it in your data source for your table.

NSArray *pictures; //Array containing all of the pictures to display
srandomdev();
NSArray *randomPictures = [pictures sortedArrayUsingComparator:(NSComparisonResult)^(id obj1, id obj2) {
    long val = random();
    if(val & 1) return NSOrderedAscending;
    return NSOrderedSame; //or NSOrderedDescending
}];

OTHER TIPS

If you always have the same set of elements, and you just want to put them into a randomized order, then I recommend you read up on the Fisher-Yates shuffling algorithm (http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). It's the same process you'd use to randomize a deck of cards in a card game, or any other finite set you want to permute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top