jeudi 22 septembre 2016

Swift: Getting EXC_BAD_INSTRUCTION when trying to append random array elements

I am getting the error, "Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)" when trying to append random array elements into a new array.

The debug log says "fatal error: Index out of range"

//If there are more than 6 players prioritizing the event, make a random choice. garudaLocations is an array containing the players who prioritized the event "Garuda".

    if garudaLocations.count > 6 {

        var finalGarudaPlayers : [Int] = []
        let getRandom = randomSequenceGenerator(1, max: garudaLocations.count) //Tell RNG how many numbers it has to pick from.
        var randomGarudaPrioritiesIndex = Int()
        for _ in 1...6 {
            randomGarudaPrioritiesIndex = getRandom() //Generate a random number.
            finalGarudaPlayers.append(garudaLocations[randomGarudaPrioritiesIndex]) //ERROR: Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)
        }
        debugPrint(finalGarudaPlayers) //Print array with the final priority Garuda members.

randomSequenceGenerator is a function I got from here, which does work to generate the random numbers.

 func randomSequenceGenerator(min: Int, max: Int) -> () -> Int {
    var numbers: [Int] = []
    return {
        if numbers.count == 0 {
            numbers = Array(min ... max)
        }

        let index = Int(arc4random_uniform(UInt32(numbers.count)))
        return numbers.removeAtIndex(index)
    }
}

To get a better understanding, I am trying to write a piece of a "team making" program where players are automatically sorted into events, but they can choose which events they would like to prioritize.

I can only have 6 people per event, however, so the goal is to take the existing garudaLocations array, choose a random 6 index locations, and get rid of the rest of the players.

I get the error only after I submit more than 6 players to the same event.

Any help is very much appreciated!




Aucun commentaire:

Enregistrer un commentaire