Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number generate issue in swift language - EXC_BAD_INSTRUCTION

I tried to generate an array with strings in random order, but always got the error "Thread1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" at the end of function randomPile. Below is my code:

import UIKit

class RandomView: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    var cardOrder = ["HeartSix","HeartNine", "ClubQueen", "SpadeKing" ]

    // cannot randomlize due to the lanuage drawbacks.
    cardOrder = randomPile(cardOrder)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// random the order of the original card pile
func randomPile(arrayPile: String[]) -> String[] {
    var arry = arrayPile
    for( var i = arry.count-1; i > 0; --i){
        var r = Int(arc4random())%(i+1)
        var a = arry[r]
        arry[r] = arry[i]
        arry[i] = a

    }
    return arry
}    
}
like image 658
Peterxwl Avatar asked Dec 12 '25 10:12

Peterxwl


1 Answers

Not an answer, presented here for code formation:

This works for me both in a playground and in an app:

var cardOrder: String[] = ["HeartSix","HeartNine", "ClubQueen", "SpadeKing" ]
println(cardOrder)

cardOrder = randomPile(cardOrder)
println(cardOrder)

Perhaps the error is elsewhere.

Note: var r = Int(arc4random_uniform(UInt32(i+1))) is both simpler and avoids bias.

like image 189
zaph Avatar answered Dec 14 '25 06:12

zaph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!