Hi, this is my way:
...
NSMutableArray * cards = [[NSMutableArray alloc] initWithObjects:nil];
int numberOfAvaiblesCardImages = 20;
int numberOfCardsInTheGame = 24;
for (int a=0; a< numberOfCardsInTheGame / 2; a++)
{
int r = -1;
bool tryAgain = true;
while (tryAgain==true)
{
tryAgain = false;
r = (arc4random() % numberOfAvaiblesCardImages)+1;
for (int i = 0; i < [cards count]; i++) {
int e = [[cards objectAtIndex:i]intValue];
if (e==r) {
tryAgain=true;
}
}
if ([cards count]==0)
{
tryAgain=false;
}
}
[cards insertObject:[NSNumber numberWithInt:r] atIndex:(a*2)];
[cards insertObject:[NSNumber numberWithInt:r] atIndex:1+(a*2)];
}
for(NSUInteger i = [cards count]; i > 1; i--) {
NSUInteger j = random_below(i);
[cards exchangeObjectAtIndex:i-1 withObjectAtIndex:j];
}
....
At this point you have a NSMutableArray with numberOfCardsInTheGame / 2 pair of card...
The method "random_below" is:
static NSUInteger random_below(NSUInteger n) {
NSUInteger m = 1;
// Compute smallest power of two greater than n.
// There's probably a faster solution than this loop, but bit-twiddling
// isn't my specialty.
do {
m <<= 1;
} while(m < n);
NSUInteger ret;
do {
ret = random() % m;
} while(ret >= n);
return ret;
}
I hope this can help you.
Nando