8

I'm having problems with this drawRandomCard function.

It works just like it should for some time, but eventually it crashes the application.

Here is the code:

import Foundation


var cardDeck = Array<PlayingCard>()

class Deck {

    func addCard(card : PlayingCard , atTop : Bool = false){

        if atTop {
            cardDeck.insert(card, atIndex: 0);
        }else{
            cardDeck += card
        }
    }

    func drawRandomCard() -> PlayingCard{
        var card = PlayingCard()
        var randomNumber : Int = Int(arc4random()) % (cardDeck.count - 1)
        card = cardDeck[randomNumber]
        cardDeck.removeAtIndex(randomNumber)
        return card
    }

}
vyudi
  • 828
  • 2
  • 9
  • 22
  • How does your code crash? Is there a stack trace or error message? Your code as posted on Github seems to have a number of compilation errors. – Craig Otis Jun 09 '14 at 11:56

2 Answers2

37

Use arc4random_uniform to avoid modulo bias. Like following:

let randomNumber = arc4random_uniform(150)

For your example, it will be:

let randomNumber = Int(arc4random_uniform(UInt32(cardDeck.count)))
orkoden
  • 18,946
  • 4
  • 59
  • 50
Adam
  • 26,549
  • 8
  • 62
  • 79
-4

Try this: Int(rand()) instead of arc4random()

Alexey Sidorov
  • 846
  • 1
  • 9
  • 17
  • 1
    How would this alleviate the crashing? I'm not saying it doesn't, but without an explanation I don't see the difference. – Craig Otis Jun 09 '14 at 11:57
  • thanks for the suggestion, worked really well. – vyudi Jun 09 '14 at 12:19
  • the arc4random() don't work well with Int type – vyudi Jun 09 '14 at 12:20
  • 1
    missing any kind of explanation why to use rand instead of arc4random – Vojtech Vrbka Dec 31 '14 at 10:58
  • 1
    The amazing thing about this really bad answer is that it has two up votes! To be clear:` rand()` is a terrible random number generator and requires seeding, it should not be used. `arc4random()` and `arc4random_uniform()` generate cryptographically good random numbers and require no seeding. – zaph Jun 01 '15 at 23:28