【问题标题】:Random array range 1-4 with each number only printed twice随机数组范围 1-4,每个数字只打印两次
【发布时间】:2014-10-24 18:38:11
【问题描述】:

我正在尝试学习如何将数字 1 到 4 的范围分配给一个数组,每个数字打印两次。我不知道如何使用随机范围来打印特定数量的数字。

不确定这是否正确。我还没有真正使用过 for 循环,但我确实学习过它们。由于如何做到这一点的障碍,甚至没有完成。

顺便说一句,说这是我正在制作的卡片配对游戏也可能会有所帮助,所以这就是为什么我只需要打印两次。

/*for index in imageArray
    {
    imageArray[index] =
    }*/

【问题讨论】:

  • 你能粘贴你用来打印值的代码吗?这可能有助于修复它

标签: arrays random swift


【解决方案1】:

将数字 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
    }

}

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多