开发者

Do you know how to randomly populate a table with an array of pictures?

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 enligh开发者_JS百科ten me?


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
}];


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜