我正在尝试学习如何将一个数字1到4的范围分配给一个数组,每个数字打印两次。我无法弄清楚如何使用随机范围来打印特定次数的数字。
不确定这是否正确。我还没有真正使用for循环,但我确实学过它们。由于如何做到这一点的障碍,甚至还没有完成。
顺便说一句,也可能有助于说这是我正在制作的卡片匹配游戏,所以这就是为什么我只需要打印两次。
/*for index in imageArray
{
imageArray[index] =
}*/
要将数字1到4分配给数组:
let numbers = Array(1...4)
将数字1到4两次分配给数组:
let numbers = Array(1...4) + Array(1...4)
要洗牌这些数字:
var shuffledNumbers = numbers.shuffled()
在Swift 4.2及更高版本中,您可以使用内置的shuffled
方法。在早期版本中,您必须自己编写,例如使用Fisher-Yates算法:
// see http://stackoverflow.com/a/24029847/1271826
extension MutableCollection {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
if count < 2 { return } // empty and single-element collections don't shuffle
for i in 0 ..< count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i)))
if j != 0 {
let current = index(startIndex, offsetBy: i)
let swapped = index(current, offsetBy: j)
swapAt(current, swapped)
}
}
}
/// Return shuffled collection the elements of `self`.
func shuffled() -> Self {
var results = self
results.shuffle()
return results
}
}