Shuffle 构建状态

为 Swift 4.2 之前的版本,为任何 Collection 添加 shuffled() 方法,为任何 MutableCollection 添加 shuffle() 方法。

它尽可能懒惰地对集合进行洗牌,而无需修改集合。 集合的索引被复制到一个数组,然后对该数组进行洗牌。

这允许仅对输入集合进行索引。 通常,这应最大限度地减少内存分配,例如,在 Element 的大小大于 Index 的大小的情况下。

对于 Swift 4.2 及更高版本,标准库的 Collection.shuffle()Collection.randomElement() 性能会好得多。 虽然有可能创建一些例子,其中使用此包中的方法能够获得更好的性能,但它们无疑是少之又少的。

示例

import Shuffle

let a = Array(0...4)

var stats = Array<Array<Int>>(repeating: Array(repeating: 0, count: a.count), count: a.count)

(0..<8000).forEach {
  _ in
  for (i,j) in a.shuffled().enumerated()  // shuffled() used here
  {
    stats[i][j] += 1
  }
}

var sums = Array<Int>(repeating: 0, count: a.count)
for total in stats
{
  let t = total.reduce(0, +)
  for i in 0..<sums.count
  {
    sums[i] += total[i]
  }
  print(total, t)
}
print(sums)