在swift中打印随机值

时间:2015-02-13 18:38:36

标签: ios iphone swift ios8

所以我在swift中玩了一些WatchKit的想法,并决定制作一个随机的扑克牌生成器。附图显示了我运行" shuffle"时的代码和输出。功能。注意输出似乎如何将2个值放在一起,从看似无处添加随机数值,它甚至还显示了12个黑桃选项,即使没有输入" 12"在values数组中。

我是编程的新手,我只是为了解决一些想法并获得快速掌握。所以任何人都可以帮助我理解为什么会发生这种情况以及如何防止它?

非常感谢先生们。Code for the shuffle method as well as output when the function is called

2 个答案:

答案 0 :(得分:0)

您可以考虑先创建套牌然后将其改组。类似的东西:

var deck = [String]()
for value in values {
    for suite in suites {
        deck.append(value+suite)
    }
 }

var shuffledDeck = [String]()
for i in 0..<52 {
    let seed = UInt32(deck.count - 1)
    let randomCardIndex = Int(arc4random_uniform(seed))
    shuffledDeck.append(deck.removeAtIndex(randomCardIndex))
}

答案 1 :(得分:0)

以@Jeremy Pope的答案为基础,我的old answers之一是一个操场,展示了如何随机播放52个随机物品。

import Foundation

extension Array
{
    func shuffled() -> Array
    {
        var result:Array = []

        result.append( self[0] )

        for index in 0..<self.count
        {
            let j = Int( arc4random_uniform( UInt32( index ) ) )
            result.append( result[ j ] )
            result[ j ] = self[ index ]
        }

        return result ;
    }
}

let suits = ["♠️", "♥️", "♣️", "♦️"]
let ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
var stringArray = Array(0...51).map { number in
    "\(suits[number / 13])\(ranks[number % 13])"
}
stringArray = stringArray.shuffled()

结果:

  

[♥️8,♣️7,♠️4,♦️J,♦️10,♦️7,♠️A,♠️9,♥️A,♥️7,♦️4,♠️8,♠️A,   ♦️A,♠️2,♠️3,♣️6,♣️2,♣️A,♥️5,♥️K,♣️10,♦️3,♥️3,♥️2,♠️6,♣️J,   ♠️10,♥️9,♦️5,♠️5,♠️7,♦️9,♣️4,♣️Q,♣️8,♠️K,♦️6,♥️J,♣️5,♠️J,   ♣️9,♦️8,♥️4,♥️10,♥️Q,♦️2,♦️Q,♦️K,♣️3,♥️6,♠️Q,♣️K]