随机数以快速语言生成问题 - EXC_BAD_INSTRUCTION

时间:2014-07-01 01:43:15

标签: xcode swift exc-bad-instruction

我尝试以随机顺序生成一个包含字符串的数组,但在函数randomPile的末尾总是出现错误“Thread1:EXC_BAD_INSTRUCTION(code = EXC_I386_INVOP,subcode = 0x0)”。以下是我的代码:

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
}    
}

2 个答案:

答案 0 :(得分:3)

这里没有给出代码形成的答案:

这适用于我在游乐场和应用程序中:

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

cardOrder = randomPile(cardOrder)
println(cardOrder)

也许错误在其他地方。

注意:var r = Int(arc4random_uniform(UInt32(i+1)))既简单又避免偏见。

答案 1 :(得分:1)

也不是答案,因为我也可以在游乐场跑步,所以我不知道你的问题在哪里。但是,没有必要创建一个新的数组引用并返回它。我还实现了一个Fisher-Yates shuffle变体,它适用于排除其上限的整数PRNG,如arc4random_uniform所做的那样:

func randomPile(myArray: String[]) -> Void {
    for i in 0..(myArray.count - 1) {
        let j = Int(arc4random_uniform(UInt32(myArray.count - i))) + i
        let tmp = myArray[i]
        myArray[i] = myArray[j]
        myArray[j] = tmp
    }
}

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

在您的阵列上调用此内容后,它会被随机播放,无需重新分配给cardOrder

附录 - 我刚检查过,由于cardOrder没有再出现在作业的左侧,因此可以使用let声明。

您还可以将随机播放功能设为通用,为什么不呢?

func shuffle<T>(myArray: T[]) -> Void {
    for i in 0..(myArray.count - 1) {
        let j = Int(arc4random_uniform(UInt32(myArray.count - i))) + i
        let tmp:T = myArray[i]
        myArray[i] = myArray[j]
        myArray[j] = tmp
    }
}

let cardOrder: String[] = ["HeartSix","HeartNine", "ClubQueen", "SpadeKing"]
println(cardOrder)  // [HeartSix, HeartNine, ClubQueen, SpadeKing]
shuffle(cardOrder)
println(cardOrder)  // sample result: [SpadeKing, HeartNine, HeartSix, ClubQueen]
let intValues = [1,2,3,4,5,6,7,8,9,10]
println(intValues)  // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(intValues)
println(intValues)  // sample result: [3, 10, 8, 4, 9, 7, 1, 2, 5, 6]