如何在Swift中对数组进行混洗?


305

如何在Swift中随机或随机排列数组中的元素?例如,如果我的阵列由52张扑克牌,我想洗牌的阵列,以洗牌。


2
这并非特定于任何语言。只需应用任何改组算法...
Gabriele Petronella 2014年

8
@Mithrandir这是不对的。在Ruby中,人们会选择array.shuffle。无需实现自己的版本。我猜OP正在寻找类似的东西。
Linus Oleander 2014年

1
但是请注意,不要仅使用任何随机播放算法来随机播放一副纸牌。
njzk2

Answers:


626

这个答案详细说明了如何在Swift 4.2+中使用快速统一的算法(Fisher-Yates)进行改组,以及如何在各个早期版本的Swift中添加相同的功能。每个Swift版本的命名和行为都与该版本的变异和非变异排序方法匹配。

迅捷4.2+

shuffle并且shuffled是Swift 4.2的原生版本。用法示例:

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

let fiveStrings = stride(from: 0, through: 100, by: 5).map(String.init).shuffled()
// fiveStrings == ["20", "45", "70", "30", ...]

var numbers = [1, 2, 3, 4]
numbers.shuffle()
// numbers == [3, 2, 1, 4]

Swift 4.0和4.1

这些扩展将shuffle()方法添加到任何可变集合(数组和不安全的可变缓冲区),并shuffled()在任何序列上添加方法:

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)) {
            // Change `Int` in the next line to `IndexDistance` in < Swift 4.1
            let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            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
    }
}

与上述Swift 4.2示例中的用法相同。


迅捷3

这些扩展将shuffle()方法添加到任何可变集合中,并将shuffled()方法添加到任何序列中:

extension MutableCollection where Indices.Iterator.Element == Index {
    /// 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)) {
            // Change `Int` in the next line to `IndexDistance` in < Swift 3.2
            let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            self.swapAt(firstUnshuffled, i)
        }
    }
}

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

与上述Swift 4.2示例中的用法相同。


迅捷2

(过时的语言:自2018年7月起,您将无法使用Swift 2.x在iTunes Connect上发布)

extension MutableCollectionType where Index == Int {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffleInPlace() {
        // empty and single-element collections don't shuffle
        if count < 2 { return }

        for i in startIndex ..< endIndex - 1 {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            guard i != j else { continue }
            swap(&self[i], &self[j])
        }
    }
}

extension CollectionType {
    /// Return a copy of `self` with its elements shuffled.
    func shuffle() -> [Generator.Element] {
        var list = Array(self)
        list.shuffleInPlace()
        return list
    }
}

用法:

[1, 2, 3].shuffle()
// [2, 3, 1]

let fiveStrings = 0.stride(through: 100, by: 5).map(String.init).shuffle()
// ["20", "45", "70", "30", ...]

var numbers = [1, 2, 3, 4]
numbers.shuffleInPlace()
// [3, 2, 1, 4]

斯威夫特1.2

(过时的语言:自2018年7月起,您将无法使用Swift 1.x在iTunes Connect上发布)

shuffle 作为变异数组方法

通过此扩展,您可以Array在适当的位置随机排列一个可变实例:

extension Array {
    mutating func shuffle() {
        if count < 2 { return }
        for i in 0..<(count - 1) {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            swap(&self[i], &self[j])
        }
    }
}
var numbers = [1, 2, 3, 4, 5, 6, 7, 8]
numbers.shuffle()                     // e.g., numbers == [6, 1, 8, 3, 2, 4, 7, 5]

shuffled 作为非变异数组方法

通过此扩展,您可以检索Array实例的随机组合副本:

extension Array {
    func shuffled() -> [T] {
        if count < 2 { return self }
        var list = self
        for i in 0..<(list.count - 1) {
            let j = Int(arc4random_uniform(UInt32(list.count - i))) + i
            swap(&list[i], &list[j])
        }
        return list
    }
}
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let mixedup = numbers.shuffled()     // e.g., mixedup == [6, 1, 8, 3, 2, 4, 7, 5]

1
如果您想要Swift 1.2中的函数版本,它需要进行一些更新countElements,然后替换count,现在返回a,T.Index.Distance因此约束条件为on C.Index.Distance == Int。这个版本应该可以使用:gist.github.com/airspeedswift/03d07a9dc86fabdc370f
Airspeed Velocity

2
这些是实际输出,Fisher-Yates应该返回源的无偏随机排列,因此不需要移动特定元素。这里一个保证,没有元件运动超过一次,但有时“移动”是相同的索引。最简单的情况是考虑- 每次都会[1, 2].shuffled()返回[2, 1]吗?
Nate Cook

1
if count > 0在变异数组函数的顶部添加了代码,以防止在传递空数组时收到“致命错误:无法形成范围为end <start的Range”。
2015年

3
@Jan:是的,guard i != j else { continue }在交换之前添加。我提起了雷达,但是新行为是故意的。
Nate Cook 2015年

3
shuffleInPlace如果集合索引不是从零开始的,例如对于数组切片,实际上可能会崩溃。for i in 0..<count - 1 应该是这样for i in startIndex ..< endIndex - 1(然后向Swift 3的转换几乎变得微不足道了)。
Martin R

131

编辑:如其他答案所述,Swift 4.2 最终将随机数生成添加到标准库,并完成了数组改组。

但是,GameplayKit中的GKRandom/ GKRandomDistribution套件对于新RandomNumberGenerator协议仍然可以使用-如果您向GameplayKit RNG添加扩展以符合新的标准库协议,则可以轻松获得:

  • 可发送的RNG(可以在测试需要时重现“随机”序列)
  • 牺牲鲁棒性以提高速度的RNG
  • 产生非均匀分布的RNG

...并仍然使用Swift中新的“本机”随机API。

该答案的其余部分与此类RNG和/或它们在较早的Swift编译器中的使用有关。


这里已经有一些不错的答案,以及一些很好的说明,说明如果不注意,编写自己的随机播放为什么会容易出错。

在iOS 9,macOS 10.11和tvOS 9(或更高版本)中,您不必自己编写。有一个有效的,正确的执行费雪耶茨在GameplayKit(其中,尽管名称,不只是游戏)。

如果您只想进行独特的洗牌:

let shuffled = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: array)

如果您希望能够复制随机排列或一系列随机排列,请选择一个特定的随机源并为其设定种子;例如

let lcg = GKLinearCongruentialRandomSource(seed: mySeedValue)
let shuffled = lcg.arrayByShufflingObjects(in: array)

在iOS 10 / macOS 10.12 / tvOS 10中,还有一种方便的语法,可通过扩展使用进行改组NSArray。当然,当您使用Swift时Array,这会有些麻烦(并且当返回Swift时,它会丢失其元素类型):

let shuffled1 = (array as NSArray).shuffled(using: random) // -> [Any]
let shuffled2 = (array as NSArray).shuffled() // use default random source

但是很容易为它创建一个保留类型的Swift包装器:

extension Array {
    func shuffled(using source: GKRandomSource) -> [Element] {
        return (self as NSArray).shuffled(using: source) as! [Element]
    }
    func shuffled() -> [Element] {
        return (self as NSArray).shuffled() as! [Element]
    }
}
let shuffled3 = array.shuffled(using: random)
let shuffled4 = array.shuffled()

6
让我想知道我从未探索过的GameplayKit中还有哪些其他有用的实用程序!
理查德·文布尔

6
图形搜索,树形搜索,规则系统... 在游戏设计和其他方面都有很多帮助的东西
rickster

5
在Swift 3 / iOS 10中,该let shuffled = lcg.arrayByShufflingObjects(in: array)
字段

30

Swift 2.0中,GameplayKit可能会抢救出来!(受iOS9或更高版本支持)

import GameplayKit

func shuffle() {
    array = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(array)
}

5
导入GameplayKit只是为了获得改组数组听起来不是一个好主意
Lope

3
为什么?它是系统的一部分,不会添加到二进制文件中。
阿比森

3
您也可以将导入的范围简单地设置为import GameplayKit.GKRandomSource
JRG-Developer

26

这可能更短一些:

sorted(a) {_, _ in arc4random() % 2 == 0}

1
@moby该sort函数需要关闭才能对元素进行排序。此闭包采用两个参数(elem1,elem2),如果第一个值应出现在第二个值之前,则必须返回true,否则返回false。如果我们改为返回一个随机布尔值……那么我们
就把

2
这里有任何数学家要确认或否定吗?
Jean Le Moignan 2014年

9
正如pjs针对另一个非常相似的答案所指出的那样,这将不会产生均匀的结果分布。使用Nate Cook的答案所示的Fisher-Yates Shuffle
罗布2014年

1
这是一个聪明的把戏,但就混洗的质量而言却是令人讨厌的。首先,此闭包应使用arc4random_uniform(),因为当前受模偏差的影响。其次,输出在很大程度上取决于排序算法(如果不查看源代码,这是我们所不知道的)。
亚历山大-恢复莫妮卡

1
继续采用这种更简单的方法,这似乎效果很好: collection.sorted { _,_ in arc4random_uniform(1) == 0 }
markiv

7

Nate的算法为例,我想看看Swift 2和协议扩展的外观。

这就是我想出的。

extension MutableCollectionType where Self.Index == Int {
    mutating func shuffleInPlace() {
        let c = self.count
        for i in 0..<(c - 1) {
            let j = Int(arc4random_uniform(UInt32(c - i))) + i
            swap(&self[i], &self[j])
        }
    }
}

extension MutableCollectionType where Self.Index == Int {
    func shuffle() -> Self {
        var r = self
        let c = self.count
        for i in 0..<(c - 1) {
            let j = Int(arc4random_uniform(UInt32(c - i))) + i
            swap(&r[i], &r[j])
        }
        return r
    }
}

现在,任何人MutableCollectionType只要将其Int用作Index


6

就我而言,我在交换数组中的对象时遇到了一些问题。然后我挠着头,去重新发明轮子。

// swift 3.0 ready
extension Array {

    func shuffled() -> [Element] {
        var results = [Element]()
        var indexes = (0 ..< count).map { $0 }
        while indexes.count > 0 {
            let indexOfIndexes = Int(arc4random_uniform(UInt32(indexes.count)))
            let index = indexes[indexOfIndexes]
            results.append(self[index])
            indexes.remove(at: indexOfIndexes)
        }
        return results
    }

}

5

这是NateSwift 4 (Xcode 9)实现Fisher-Yates随机播放的版本。

extension MutableCollection {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffle() {
        for i in indices.dropLast() {
            let diff = distance(from: i, to: endIndex)
            let j = index(i, offsetBy: numericCast(arc4random_uniform(numericCast(diff))))
            swapAt(i, j)
        }
    }
}

extension Collection {
    /// Return a copy of `self` with its elements shuffled
    func shuffled() -> [Element] {
        var list = Array(self)
        list.shuffle()
        return list
    }
}

更改为:

  • Indices.Iterator.Element == Index现在,约束已成为Collection协议的一部分,并且不再需要对扩展施加任何约束。
  • 元素交换必须通过调用swapAt()集合来完成,比较SE-0173 AddMutableCollection.swapAt(_:_:)
  • Element是的别名Iterator.Element

3

这是我用的:

func newShuffledArray(array:NSArray) -> NSArray {
    var mutableArray = array.mutableCopy() as! NSMutableArray
    var count = mutableArray.count
    if count>1 {
        for var i=count-1;i>0;--i{
            mutableArray.exchangeObjectAtIndex(i, withObjectAtIndex: Int(arc4random_uniform(UInt32(i+1))))
        }
    }
    return mutableArray as NSArray
}

3

Swift 4 在for循环中随机排列数组的元素,其中i是混合比

var cards = [Int]() //Some Array
let i = 4 // is the mixing ratio
func shuffleCards() {
    for _ in 0 ..< cards.count * i {
        let card = cards.remove(at: Int(arc4random_uniform(UInt32(cards.count))))
        cards.insert(card, at: Int(arc4random_uniform(UInt32(cards.count))))
    }
}

或带有扩展名Int

func shuffleCards() {
    for _ in 0 ..< cards.count * i {
        let card = cards.remove(at: cards.count.arc4random)
        cards.insert(card, at: cards.count.arc4random)
    }
}
extension Int {
    var arc4random: Int {
        if self > 0 {
            print("Arc for random positiv self \(Int(arc4random_uniform(UInt32(self))))")
        return Int(arc4random_uniform(UInt32(self)))
        } else if self < 0 {
            print("Arc for random negotiv self \(-Int(arc4random_uniform(UInt32(abs(self)))))")
            return -Int(arc4random_uniform(UInt32(abs(self))))
        } else {
            print("Arc for random equal 0")
            return 0
        }
    }
}

2

@Nate Cook回答以下的Swift 3解决方案:(如果索引以0开头,则工作,请参见下面的注释)

extension Collection {
    /// Return a copy of `self` with its elements shuffled
    func shuffle() -> [Generator.Element] {
        var list = Array(self)
        list.shuffleInPlace()
        return list
    } }

extension MutableCollection where Index == Int {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffleInPlace() {
        // empty and single-element collections don't shuffle
        if count < 2 { return }
        let countInt = count as! Int

    for i in 0..<countInt - 1 {
        let j = Int(arc4random_uniform(UInt32(countInt - i))) + i
            guard i != j else { continue }
            swap(&self[i], &self[j])
        }
    }
}

1
如果集合索引确实从0开始(例如对于数组切片),则可能会崩溃。尝试运行var a = [1, 2, 3, 4, 5, 6][3..<6]; a.shuffleInPlace()几次。–请参阅stackoverflow.com/a/37843901/1187415,以获取正确的解决方案。
Martin R

2

这是最简单的方法。import Gamplaykit到您的VC,并使用以下代码。在Xcode 8中测试。

 import GameplayKit

 let array: NSArray = ["Jock", "Ellie", "Sue Ellen", "Bobby", "JR", "Pamela"]

 override func viewDidLoad() {
    super.viewDidLoad()

    print(array.shuffled())  
}

如果要从数组中获取经过改组的字符串,则可以使用以下代码。

func suffleString() {

    let ShuffleArray = array.shuffled()

    suffleString.text = ShuffleArray.first as? String

    print(suffleString.text!)

}

2

使用Swift 3,如果您想就地重组数组或从数组中获得新的重组数组,AnyIterator可以为您提供帮助。这个想法是从您的数组中创建一个索引数组,用AnyIterator实例和swap(_:_:)函数将这些索引改组,并映射此索引的每个元素AnyIterator与数组的对应元素。


以下Playground代码展示了其工作原理:

import Darwin // required for arc4random_uniform

let array = ["Jock", "Ellie", "Sue Ellen", "Bobby", "JR", "Pamela"]
var indexArray = Array(array.indices)
var index = indexArray.endIndex

let indexIterator: AnyIterator<Int> = AnyIterator {
    guard let nextIndex = indexArray.index(index, offsetBy: -1, limitedBy: indexArray.startIndex)
        else { return nil }

    index = nextIndex
    let randomIndex = Int(arc4random_uniform(UInt32(index)))
    if randomIndex != index {
        swap(&indexArray[randomIndex], &indexArray[index])
    }

    return indexArray[index]
}

let newArray = indexIterator.map { array[$0] }
print(newArray) // may print: ["Jock", "Ellie", "Sue Ellen", "JR", "Pamela", "Bobby"]

您可以重构先前的代码并shuffled()Array扩展内创建函数,以便从数组中获取新的随机数组:

import Darwin // required for arc4random_uniform

extension Array {

    func shuffled() -> Array<Element> {
        var indexArray = Array<Int>(indices)        
        var index = indexArray.endIndex

        let indexIterator = AnyIterator<Int> {
            guard let nextIndex = indexArray.index(index, offsetBy: -1, limitedBy: indexArray.startIndex)
                else { return nil }

            index = nextIndex                
            let randomIndex = Int(arc4random_uniform(UInt32(index)))
            if randomIndex != index {
                swap(&indexArray[randomIndex], &indexArray[index])
            }

            return indexArray[index]
        }

        return indexIterator.map { self[$0] }
    }

}

用法:

let array = ["Jock", "Ellie", "Sue Ellen", "Bobby", "JR", "Pamela"]
let newArray = array.shuffled()
print(newArray) // may print: ["Bobby", "Pamela", "Jock", "Ellie", "JR", "Sue Ellen"]
let emptyArray = [String]()
let newEmptyArray = emptyArray.shuffled()
print(newEmptyArray) // prints: []

作为前面代码的替代方法,您可以shuffle()Array扩展内创建一个函数,以便在适当位置随机排列数组:

import Darwin // required for arc4random_uniform

extension Array {

    mutating func shuffle() {
        var indexArray = Array<Int>(indices)
        var index = indexArray.endIndex

        let indexIterator = AnyIterator<Int> {
            guard let nextIndex = indexArray.index(index, offsetBy: -1, limitedBy: indexArray.startIndex)
                else { return nil }

            index = nextIndex                
            let randomIndex = Int(arc4random_uniform(UInt32(index)))
            if randomIndex != index {
                swap(&indexArray[randomIndex], &indexArray[index])
            }

            return indexArray[index]
        }

        self = indexIterator.map { self[$0] }
    }

}

用法:

var mutatingArray = ["Jock", "Ellie", "Sue Ellen", "Bobby", "JR", "Pamela"]
mutatingArray.shuffle()
print(mutatingArray) // may print ["Sue Ellen", "Pamela", "Jock", "Ellie", "Bobby", "JR"]

1

您还可以使用泛型swap函数并实现提到的Fisher-Yates:

for idx in 0..<arr.count {
  let rnd = Int(arc4random_uniform(UInt32(idx)))
  if rnd != idx {
    swap(&arr[idx], &arr[rnd])
  }
}

或更详细:

for idx in 0..<steps.count {
  swap(&steps[idx], &steps[Int(arc4random_uniform(UInt32(idx)))])
}

2
这至少会受到此处描述的一个错误的严重影响从而始终将一个值从其原始位置交换出去。对此进行了补救let rnd = Int(arc4random_uniform(UInt32(idx + 1)))。此外,在风云,你一般迭代从arr.count - 1下到1(或者,如果你从迭代0arr.count - 1,你选择指数像内特节目中接受的答案)。参见Fisher-Yates讨论的“ 现代算法”部分
罗布2014年

1

作品!!。生物是要洗牌的阵列。

extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

var organisms = [
    "ant",  "bacteria", "cougar",
    "dog",  "elephant", "firefly",
    "goat", "hedgehog", "iguana"]

print("Original: \(organisms)")

organisms.shuffle()

print("Shuffled: \(organisms)")


0

这是在Swift 3.0中使用种子将一个数组改组的方法。

extension MutableCollection where Indices.Iterator.Element == Index {
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }


        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            srand48(seedNumber)
            let number:Int = numericCast(unshuffledCount)
            let r = floor(drand48() * Double(number))

            let d: IndexDistance = numericCast(Int(r))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}


0

这是我用的:

import GameplayKit

extension Collection {
    func shuffled() -> [Iterator.Element] {
        let shuffledArray = (self as? NSArray)?.shuffled()
        let outputArray = shuffledArray as? [Iterator.Element]
        return outputArray ?? []
    }
    mutating func shuffle() {
        if let selfShuffled = self.shuffled() as? Self {
            self = selfShuffled
        }
    }
}

// Usage example:

var numbers = [1,2,3,4,5]
numbers.shuffle()

print(numbers) // output example: [2, 3, 5, 4, 1]

print([10, "hi", 9.0].shuffled()) // output example: [hi, 10, 9]

0

简单的例子:

extension Array {
    mutating func shuffled() {
        for _ in self {
            // generate random indexes that will be swapped
            var (a, b) = (Int(arc4random_uniform(UInt32(self.count - 1))), Int(arc4random_uniform(UInt32(self.count - 1))))
            if a == b { // if the same indexes are generated swap the first and last
                a = 0
                b = self.count - 1
            }
            swap(&self[a], &self[b])
        }
    }
}

var array = [1,2,3,4,5,6,7,8,9,10]
array.shuffled()
print(array) // [9, 8, 3, 5, 7, 6, 4, 2, 1, 10]

0

工作数组扩展(变异和非变异)

Swift 4.1 / Xcode 9

不建议使用最高答案,因此我自己创建了自己的扩展以在最新版本的Swift 4.1(Xcode 9)中对数组进行随机组合:

extension Array {

// Non-mutating shuffle
    var shuffled : Array {
        let totalCount : Int = self.count
        var shuffledArray : Array = []
        var count : Int = totalCount
        var tempArray : Array = self
        for _ in 0..<totalCount {
            let randomIndex : Int = Int(arc4random_uniform(UInt32(count)))
            let randomElement : Element = tempArray.remove(at: randomIndex)
            shuffledArray.append(randomElement)
            count -= 1
        }
        return shuffledArray
    }

// Mutating shuffle
    mutating func shuffle() {
        let totalCount : Int = self.count
        var shuffledArray : Array = []
        var count : Int = totalCount
        var tempArray : Array = self
        for _ in 0..<totalCount {
            let randomIndex : Int = Int(arc4random_uniform(UInt32(count)))
            let randomElement : Element = tempArray.remove(at: randomIndex)
            shuffledArray.append(randomElement)
            count -= 1
        }
        self = shuffledArray
    }
}

呼叫非静音随机播放[Array] -> [Array]

let array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

print(array.shuffled)

array将以随机顺序打印。


呼叫变异随机播放[Array] = [Array]

var array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

array.shuffle() 
// The array has now been mutated and contains all of its initial 
// values, but in a randomized shuffled order

print(array) 

这将array按其当前顺序打印,该顺序已经随机打乱。


希望这对每个人都有用,如果您有任何问题,建议或意见,请随时提问!


0

在SWIFT 4中

func createShuffledSequenceOfNumbers(max:UInt)->[UInt] {

    var array:[UInt]! = []
    var myArray:[UInt]! = []
    for i in 1...max {
        myArray.append(i)
    }
    for i in 1...max {
        array.append(i)
    }
    var tempArray:[Int]! = []
    for index in 0...(myArray.count - 1) {

        var isNotFinded:Bool = true
        while(isNotFinded){

            let randomNumber = arc4random_uniform(UInt32(myArray.count))
            let randomIndex = Int(randomNumber)

            if(!tempArray.contains(randomIndex)){
                tempArray.append(randomIndex)

                array[randomIndex] = myArray[index]
                isNotFinded = false
            }
        }
    }

    return array
}

0

如果要使用简单的Swift For循环函数,请使用此->

var arrayItems = ["A1", "B2", "C3", "D4", "E5", "F6", "G7", "H8", "X9", "Y10", "Z11"]
var shuffledArray = [String]()

for i in 0..<arrayItems.count
{
    let randomObject = Int(arc4random_uniform(UInt32(items.count)))

    shuffledArray.append(items[randomObject])

    items.remove(at: randomObject)
}

print(shuffledArray)

使用扩展的Swift Array Suffle->

extension Array {
    // Order Randomize
    mutating func shuffle() {
        for _ in 0..<count {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

0

从Swift 4.2开始,有两个方便的功能:

// shuffles the array in place
myArray.shuffle()

// generates a new array with shuffled elements of the old array
let newArray = myArray.shuffled()

-2

这是在操场上运行的一些代码。您无需在实际的Xcode项目中导入Darwin。

import darwin

var a = [1,2,3,4,5,6,7]

func shuffle<ItemType>(item1: ItemType, item2: ItemType) -> Bool {
    return drand48() > 0.5
}

sort(a, shuffle)

println(a)

7
这样会导致结果的分布不均匀。它也将是O(n log n),其中Fisher-Yates混洗将在O(n)时间内给出均匀分布的结果。
pjs 2014年

drand48()每次都还提供相同的伪随机数,除非您设置类似的种子srand48(Int(arc4random()))
Kametrixom 2015年

-3

当我将xCode版本升级到7.4 beta时,它停在“ swap(&self [i],&self [j])”。
致命错误:不支持与自身交换位置

我找到了i = j的原因(交换功能将爆炸)

所以我添加如下条件

if (i != j){
    swap(&list[i], &list[j])
}

耶!对我来说还好。


这似乎是对克里斯的答案的评论,而不是原始问题的答案。
Mogsdad
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.