通过抽取下采样数组的有效方法?

Tru*_*an1 2 arrays downsampling swift swift3

我试图通过抽取或提取每个第X项来对长数组进行下采样.

这是我的数组扩展所得到的:

func downsampled(to threshold: Int) -> [T] {
    // Validate that threshold falls in valid range
    guard !isEmpty, 1...count ~= threshold else { return Array(self) }

    let skip = (count / threshold) + 1
    var index = 0

    var items = [T]()
    while index < count {
        items.append(self[index])
        index += skip
    }

    return items
}
Run Code Online (Sandbox Code Playgroud)

我期待原始数组中的50-100k项目,并且可能会下采样到屏幕的原生边界宽度(500-1k点).

有没有更简洁或有效的方法来做到这一点?

Leo*_*bus 5

这可能不是更有效但我认为使用步幅更简洁(从:,到:,by :),如下所示:

extension Array {
    func every(nth: Int) -> Array {
        var result: Array = []
        stride(from: 0, to: count, by: nth).forEach { result.append(self[$0]) } 
        return result
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场测试

let array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].every(nth: 2)
array  //  [1, 3, 5, 7, 9, 11, 13, 15]
Run Code Online (Sandbox Code Playgroud)