3

我试图以随机顺序生成一个包含字符串的数组,但在函数 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
}    
}
4

2 回答 2

3

不是答案,此处为代码形成提供:

这在操场和应用程序中都适用于我:

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

cardOrder = randomPile(cardOrder)
println(cardOrder)

也许错误在其他地方。

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

于 2014-07-01T02:07:46.950 回答
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]
于 2014-07-01T02:40:34.180 回答