无法在Swift中复制数组中的shuffle

时间:2017-03-06 20:05:59

标签: swift

我有两个我要改组的阵列。这是两个数组:

var allCards = ["2_of_clubs", "2_of_spades", "2_of_diamonds", "2_of_hearts", "3_of_clubs", "3_of_spades", "3_of_diamonds", "3_of_hearts", "4_of_clubs", "4_of_spades", "4_of_diamonds", "4_of_hearts", "5_of_clubs", "5_of_spades", "5_of_diamonds", "5_of_hearts", "6_of_clubs", "6_of_spades", "6_of_diamonds", "6_of_hearts", "7_of_clubs", "7_of_spades","7_of_diamonds","7_of_hearts", "8_of_clubs", "8_of_spades", "8_of_diamonds", "8_of_hearts", "9_of_clubs", "9_of_spades", "9_of_diamonds", "9_of_hearts", "10_of_clubs", "10_of_spades", "10_of_diamonds", "10_of_hearts", "jack_of_clubs", "jack_of_spades", "jack_of_diamonds", "jack_of_hearts", "queen_of_clubs", "queen_of_spades", "queen_of_diamonds", "queen_of_hearts", "king_of_clubs", "king_of_spades", "king_of_diamonds", "king_of_hearts", "ace_of_clubs", "ace_of_spades", "ace_of_diamonds", "ace_of_hearts"]

var allValues = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14]

我想平等地对它们进行洗牌,因此值2留在2个俱乐部,2个黑桃等等。我尝试使用Shuffle array swift 3How do I shuffle an array in Swift?的答案,他们声明这应该有效:

let randomIndex = UInt64(arc4random_uniform(UInt32(1000)))
let randomShuffle = GKLinearCongruentialRandomSource(seed: randomIndex)
let shuffledValues = randomShuffle.arrayByShufflingObjects(in: allValues)
let shuffledCards = randomShuffle.arrayByShufflingObjects(in: allCards)
print(shuffledValues)
print(shuffledCards)

我把它作为印刷品:

[3, 6, 5, 5, 9, 10, 11, 11, 8, 6, 5, 3, 14, 12, 3, 8, 2, 3, 10, 4, 13, 12, 7, 12, 10, 5, 12, 13, 14, 11, 2, 6, 9, 7, 10, 14, 7, 8, 6, 14, 4, 9, 13, 2, 11, 9, 4, 7, 8, 2, 13, 4]
[jack_of_clubs, 6_of_hearts, 10_of_hearts, 6_of_spades, king_of_hearts, 5_of_spades, 5_of_hearts, ace_of_diamonds, queen_of_diamonds, 10_of_spades, 7_of_hearts, queen_of_spades, 9_of_clubs, 2_of_diamonds, 3_of_hearts, 3_of_diamonds, 9_of_spades, queen_of_clubs, 8_of_clubs, 9_of_diamonds, 7_of_clubs, 3_of_spades, 8_of_spades, 8_of_hearts, 5_of_clubs, 6_of_diamonds, ace_of_spades, 2_of_spades, ace_of_clubs, 10_of_diamonds, 4_of_spades, 2_of_clubs, 10_of_clubs, king_of_diamonds, 7_of_diamonds, 6_of_clubs, 8_of_diamonds, queen_of_hearts, 9_of_hearts, jack_of_diamonds, 2_of_hearts, king_of_clubs, jack_of_spades, 4_of_hearts, 7_of_spades, 3_of_clubs, 4_of_diamonds, 4_of_clubs, king_of_spades, jack_of_hearts, ace_of_hearts, 5_of_diamonds]

两者都有相同的数量。我很好奇为什么这不起作用。是否可以编辑此代码以使其工作,否则我想知道如何对数组进行混洗并复制它。

1 个答案:

答案 0 :(得分:1)

您可以将元素与zip配对,然后随机播放,然后解压缩。

let pairs = Array(zip(allCards, allValues))

let randomIndex = UInt64(arc4random_uniform(UInt32(1000)))
let randomShuffle = GKLinearCongruentialRandomSource(seed: randomIndex)
let shuffledPairs = randomShuffle.arrayByShufflingObjects(in: pairs) as! [(String, Int)]

let shuffledCards = shuffledPairs.map { $0.0 }
let shuffledValues = shuffledPairs.map { $0.1 }