从Swift中的数组中获取随机元素

时间:2014-12-02 21:30:15

标签: arrays swift random shuffle

我有一个像:

这样的数组
var names: String = [ "Peter", "Steve", "Max", "Sandra", "Roman", "Julia" ]

我想从该数组中获取3个随机元素。我来自C#,但是我很快就不知道从哪里开始。我想我应该首先对阵列进行洗牌,然后从中挑选前3个项目?

我尝试使用以下扩展程序对其进行随机播放:

extension Array
{
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

然后它说&#34;&#39;()&#39;不可转换为&#39; [Int]&#39;&#34;在&#34; shuffle()&#34;。

的位置

选择我使用的一些元素:

var randomPicks = names[0..<4];

到目前为止看起来很不错。

如何洗牌?或者有没有人有更好/更优雅的解决方案?

5 个答案:

答案 0 :(得分:30)

Xcode 9•Swift 4

extension Array {
    /// Returns an array containing this sequence shuffled
    var shuffled: Array {
        var elements = self
        return elements.shuffle()
    }
    /// Shuffles this sequence in place
    @discardableResult
    mutating func shuffle() -> Array {
        let count = self.count
        indices.lazy.dropLast().forEach {
            swapAt($0, Int(arc4random_uniform(UInt32(count - $0))) + $0)
        }
        return self
    }
    var chooseOne: Element { return self[Int(arc4random_uniform(UInt32(count)))] }
    func choose(_ n: Int) -> Array { return Array(shuffled.prefix(n)) }
}

游乐场测试

var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
let shuffledAlphabet = alphabet.shuffled

let letter = alphabet.chooseOne

var numbers = Array(0...9)

let shuffledNumbers = numbers.shuffled
shuffledNumbers                              // [8, 9, 3, 6, 0, 1, 4, 2, 5, 7]

numbers            // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

numbers.shuffle() // mutate it  [6, 0, 2, 3, 9, 1, 5, 7, 4, 8]

numbers            // [6, 0, 2, 3, 9, 1, 5, 7, 4, 8]

let pick3numbers = numbers.choose(3)  // [8, 9, 2]

Xcode 8.3.1•Swift 3.1

import UIKit

extension Array {
    /// Returns an array containing this sequence shuffled
    var shuffled: Array {
        var elements = self
        return elements.shuffle()
    }
    /// Shuffles this sequence in place
    @discardableResult
    mutating func shuffle() -> Array {
        let count = self.count
        indices.lazy.dropLast().forEach {
            guard case let index = Int(arc4random_uniform(UInt32(count - $0))) + $0, index != $0 else { return }
            swap(&self[$0], &self[index])
        }
        return self
    }
    var chooseOne: Element { return self[Int(arc4random_uniform(UInt32(count)))] }
    func choose(_ n: Int) -> Array { return Array(shuffled.prefix(n)) }
}

答案 1 :(得分:9)

  

或者有人为此提供更好/更优雅的解决方案吗?

我愿意。在算法上优于接受的答案,它为完整的shuffle执行count-1 arc4random_uniform次操作,我们只需在 n arc4random_uniform中选择 n 值操作

实际上,我有两种方式比接受的答案做得更好:

更好的解决方案

extension Array {
    /// Picks `n` random elements (straightforward approach)
    subscript (randomPick n: Int) -> [Element] {
        var indices = [Int](0..<count)
        var randoms = [Int]()
        for _ in 0..<n {
            randoms.append(indices.remove(at: Int(arc4random_uniform(UInt32(indices.count)))))
        }
        return randoms.map { self[$0] }
    }
}

最佳解决方案

以下解决方案比前一个解决方案快两倍。

for Swift 3.0和3.1

extension Array {
    /// Picks `n` random elements (partial Fisher-Yates shuffle approach)
    subscript (randomPick n: Int) -> [Element] {
        var copy = self
        for i in stride(from: count - 1, to: count - n - 1, by: -1) {
            let j = Int(arc4random_uniform(UInt32(i + 1)))
            if j != i {
                swap(&copy[i], &copy[j])
            }
        }
        return Array(copy.suffix(n))
    }
}

适用于Swift 3.2和4.x

extension Array {
    /// Picks `n` random elements (partial Fisher-Yates shuffle approach)
    subscript (randomPick n: Int) -> [Element] {
        var copy = self
        for i in stride(from: count - 1, to: count - n - 1, by: -1) {
            copy.swapAt(i, Int(arc4random_uniform(UInt32(i + 1))))
        }
        return Array(copy.suffix(n))
    }
}

用法:

let digits = Array(0...9)  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let pick3digits = digits[randomPick: 3]  // [8, 9, 0]

答案 2 :(得分:1)

你也可以使用arc4random()从数组中选择三个元素。像这样:

extension Array {
    func getRandomElements() -> (T, T, T) {
        return (self[Int(arc4random()) % Int(count)],
                self[Int(arc4random()) % Int(count)],
                self[Int(arc4random()) % Int(count)])
    }
}

let names = ["Peter", "Steve", "Max", "Sandra", "Roman", "Julia"]
names.getRandomElements()

这只是一个例子,您还可以在函数中包含逻辑,以便为每个逻辑获取不同的名称。

答案 3 :(得分:1)

Swift 4.1及以下

let playlist = ["Nothing Else Matters", "Stairway to Heaven", "I Want to Break Free", "Yesterday"]
let index = Int(arc4random_uniform(UInt32(playlist.count)))
let song = playlist[index]

Swift 4.2及以上

if let song = playlist.randomElement() {
  print(song)
} else {
  print("Empty playlist.")
}

答案 4 :(得分:0)

您可以在Array上定义扩展名:

extension Array {
    func pick(_ n: Int) -> [Element] {
        guard count >= n else {
            fatalError("The count has to be at least \(n)")
        }
        guard n >= 0 else {
            fatalError("The number of elements to be picked must be positive")
        }

        let shuffledIndices = indices.shuffled().prefix(upTo: n)
        return shuffledIndices.map {self[$0]}
    }
}

[ "Peter", "Steve", "Max", "Sandra", "Roman", "Julia" ].pick(3)

如果初始数组可能有重复项,并且您想要值的唯一性:

extension Array where Element: Hashable {
    func pickUniqueInValue(_ n: Int) -> [Element] {
        let set: Set<Element> = Set(self)
        guard set.count >= n else {
            fatalError("The array has to have at least \(n) unique values")
        }
        guard n >= 0 else {
            fatalError("The number of elements to be picked must be positive")
        }

        return Array(set.prefix(upTo: set.index(set.startIndex, offsetBy: n)))
    }
}

[ "Peter", "Steve", "Max", "Sandra", "Roman", "Julia" ].pickUniqueInValue(3)