Shuffle NSMutableArray Tutorial: How to Shuffle a Deck of Cards

Goran on

xcode_1title

Most of puzzle games use some kind of shuffle algorithm. For example, memory games would be really boring to play without tiles shuffle before you start playing game, if you solved it once you would remember position of most tiles. Same thing is with card games, before playing game you need to shuffle deck. Very often when programming such games you’ll store values in mutable array.

// define mutable array and initialize it
 NSMutableArray *arrayExample = [[NSMutableArray alloc] init];
// add numbers 1,2,3,4 to array
 [arrayExample addObject:[NSNumber numberWithInt:1]];
 [arrayExample addObject:[NSNumber numberWithInt:2]];
 [arrayExample addObject:[NSNumber numberWithInt:3]];
 [arrayExample addObject:[NSNumber numberWithInt:4]];

After you add objects to it, array is ready for shuffling. In this example we’ll simply swap objects at each position with some random position. we have to define loop that will run that many times how many items in array are. After that we pick some random number based on array items count and we exchange object at current position with object at random position.

// shuffle array
 for (int i = 0; i < [arrayExample count]; ++i) {
 int r = (random() % [arrayExample count]);
 [arrayExample exchangeObjectAtIndex:i withObjectAtIndex:r];
 }

As a quick reminder, if you need object at specific location in array you can reach it with: [arrayExample objectAtIndex:123] – this will return 124th object in array.

I hope my post will help people who started learning XCode recently to understand NSMutableArrays a bit better.

Thanks for reading!

1 comment
  1. Michele on:

    I am currently tynirg to develop an automatic puzzle solver for my iPhone app, and it seems that TreeView may be the way forward. However, I’d really appreciate your opinion on this because it is all quite new to me!My game involves moving objects around a series of tiles, so for each position I will establish which direction the player can move, and then move in these directions, creating branches as I go. Then hopefully one of the branches will be a solution to the puzzle. Is using TreeView a good way to do this? I have no idea it’s completely new to me.Thanks in advance!

Leave Your Comment

You’re more than welcome to leave your own comment!

Just please, pretty please: don’t spam. Thank you :)