0

Im a relatively new programmer working on a card game app on Xcode, as of right now I generate a random number to determine which card gets dealt first. Im curious as to how I can prevent the same number from popping up more than once. Lets say the generator picks 52 and the Ace of Spades gets dealt, when its dealing to the next player the generator still has the possibility of picking 52 which wouldn't work because the Ace of Spades has already left the deck.

Heres a sample of my code........

(the random number goes from 27 - 52 because I only have Spades and Hearts so far)

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

//Dealing Random Cards ------------------------------------------------------------------------------------------------------

self.FirstCard = arc4random() % 26+27;
NSLog(@"Random Number: %i", self.FirstCard);

//Deal First Card --------------------------------------------------------------------
if (self.FirstCard == 52) {
    SKAction *DealFirstCard = [SKAction moveToY:40 duration:0.25];
    SKAction *DealFirstCard2 = [SKAction moveToX:130 duration:0.25];
    SKAction *DealSequence = [SKAction sequence:@[DealFirstCard,DealFirstCard2]];
    [self.ASpade runAction:DealSequence];
}
if (self.FirstCard == 51) {
    SKAction *DealFirstCard = [SKAction moveToY:40 duration:0.25];
    SKAction *DealFirstCard2 = [SKAction moveToX:130 duration:0.25];
    SKAction *DealSequence = [SKAction sequence:@[DealFirstCard,DealFirstCard2]];
    [self.TwoSpade runAction:DealSequence];
}
if (self.FirstCard == 50) {
    SKAction *DealFirstCard = [SKAction moveToY:40 duration:0.25];
    SKAction *DealFirstCard2 = [SKAction moveToX:130 duration:0.25];
    SKAction *DealSequence = [SKAction sequence:@[DealFirstCard,DealFirstCard2]];
    [self.ThreeSpade runAction:DealSequence];
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
nick
  • 101
  • 10
  • any help with how to do that? I'm not very experienced working with randoms. – nick Jan 26 '14 at 06:11
  • possible duplicate of [Non repeating random numbers](http://stackoverflow.com/questions/1617630/non-repeating-random-numbers) See also [What's the best way to shuffle an NSMutableArray?](http://stackoverflow.com/q/56648) – jscs Jan 26 '14 at 20:26

2 Answers2

1

You would need to keep a list of the previous numbers in a list. Every time you generate a number you'd need to make sure that number isn't already in your list.

T McKeown
  • 12,971
  • 1
  • 25
  • 32
0

You should shuffle the deck, then iterate through it.

pjs
  • 18,696
  • 4
  • 27
  • 56