arrays - 使用 random() [Swift, Linux] 打乱字符串数组

标签 arrays swift linux

我正在尝试使用 Glibc 的 randr 函数在 linux 中替换 arc4random。尽管我设法打乱了一个整数数组,但我未能对一个字符串数组进行打乱。

下面的代码按预期工作:

import Foundation

extension MutableCollection {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(Int(random() % numericCast(unshuffledCount) + 1 ))
            let i = index(firstUnshuffled, offsetBy: d)
            swapAt(firstUnshuffled, i)
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}

let x = [1, 2, 3].shuffled()
print(x)
// [3, 1, 2]

但是如果我对一个字符串数组做同样的事情:

let fiveStrings = ["20", "45", "70", "30"].map(String.init).shuffled()
print(fiveStrings)

失败,索引超出范围。错误与

相同
var numbers = [1, 2, 3, 4]
print(numbers.shuffle())
  • 如何使用 random() 打乱字符串?

最佳答案

代码

 let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))

How do I shuffle an array in Swift?在中创建一个随机数 在 0unshuffledCount-1 之间。为了达到同样的目的 random() 使用

 let d: IndexDistance = numericCast(Int(random() % numericCast(unshuffledCount)))

没有 +1

请注意,与 arc4random_uniform() 相比:

关于arrays - 使用 random() [Swift, Linux] 打乱字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130559/

相关文章:

ios - 为什么我不能将 ContactBody 转换为 SpriteKit 中的自定义 SKNode

java - 在linux上编译运行HelloWorld.java

linux - 如何使用iwlist扫描隐藏的ssid?

swift - 将位索引数组转换为 OptionSet

swift - iOS 11 上的程序化开始 Refreshing() 在大标题模式下存在问题

linux - 如何创建一个不阻止写入器和读取器的 linux fifo "pipe"(或其他东西)?

c - 为什么条件为假时无法退出for循环?

java - 在Java中创建多个砖 block

c - 如何在 C 的条件语句中使用字符串数组?

ios - 从 UITableView - Swift 连续编辑/更改数据的过程是什么