如何从CollectionType获取随机元素? [英] How to get random Element from CollectionType?

查看:127
本文介绍了如何从CollectionType获取随机元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的示例代码

import Foundation // ar4random_uniform

extension CollectionType where Self.Index.Distance == Int {
    var randomElement: Self.Generator.Element? {
        if !isEmpty {
            let i = Int(arc4random_uniform(UInt32(count)))
            return self[startIndex.advancedBy(i)]
        } else {
            return nil
        }
    }
}

let arr = ["alfa", "beta","gama"]
let view = "abcdefghijklmnopqrstuvwxyz".characters
let dict:Dictionary<Int,Any> = [1:"a",2:true,3:1]
let range = Range<Int>(start: -99, end: 100)
let b = UnsafeMutablePointer<Int>.alloc(10)
for i in 0..<10 { (b+i).memory = 1000*i }
let buff = UnsafeMutableBufferPointer<Int>(start: b, count: 10)
for i in 0...10 {
    print(arr.randomElement!,
        view.randomElement!,
        dict.randomElement!,
        range.randomElement!,
        buff.randomElement!)
}

/*
gama z (1, "a") 62 2000
alfa i (1, "a") 4 9000
alfa f (1, "a") 14 6000
gama g (1, "a") 68 8000
beta a (2, true) 42 7000
alfa y (1, "a") -76 1000
alfa i (1, "a") 76 4000
gama f (2, true) 79 3000
beta s (2, true) 46 3000
beta l (1, "a") -17 9000
gama q (3, 1) 62 9000
*/

代码按预期工作.

问题是,哪种Swift的内置类型符合CollectionType协议,其中Self.Index.Distance != Int以及在这种情况下如何实现相同的行为?

Question is, which Swift's build-in type conforms to CollectionType protocol where Self.Index.Distance != Int and how to implement the same behaviour in that case?

推荐答案

typealias Distance : _SignedIntegerType = Int

因此每个Index.Distance必须符合_SignedIntegerType.每个_SignedIntegerType都承诺与IntMax(最大的可用整数)之间的转换:

So every Index.Distance must conform to _SignedIntegerType. Every _SignedIntegerType promises conversion to and from IntMax (the widest available integer):

init(_: IntMax)
func toIntMax() -> IntMax

将这两个事实放在一起,我们就可以计算一个随机索引(最多2 31 -1个元素;对于大于该数量的集合会崩溃):

Put these two facts together, and we can compute a random index (up to 231-1 elements; this will crash for collections larger than that):

let randomDistance = Index.Distance(arc4random_uniform(UInt32(count.toIntMax())).toIntMax())
let randomIndex = startIndex.advancedBy(randomDistance)
return self[randomIndex]

这篇关于如何从CollectionType获取随机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆