本文介绍了通过抽取或提取Swift中的第n个元素来进行下采样收集的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试通过抽取或提取第n个元素来对长集合进行降采样.

I'm trying to downsample a long collection by decimating or extracting every nth element.

这是我对数组扩展的要求:

Here's what I got for my array extension:

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
}

我希望原始数组中有50-100k个项目,并且可能会将其降采样到屏幕的本机边界宽度(500-1k点).

I'm expecting 50-100k items in the original array and will probably downsample to the native bounds width of the screen (500-1k points).

是否有更简洁或更有效的方法?

Is there a more concise or efficient way of doing this?

推荐答案

extension RangeReplaceableCollection {
    func every(from: Index? = nil, through: Index? = nil, nth: Int) -> Self { .init(stride(from: from, through: through, by: nth)) }
}


extension Collection {
    func stride(from: Index? = nil, through: Index? = nil, by: Int) -> AnySequence<Element> {
        var index = from ?? startIndex
        let endIndex = through ?? self.endIndex
        return AnySequence(AnyIterator {
            guard index < endIndex else { return nil }
            defer { index = self.index(index, offsetBy: by, limitedBy: endIndex) ?? endIndex }
            return self[index]
        })
    }
}


游乐场测试


Playground testing

let array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
for element in array.stride(by: 3) {
    print(element)
}
array.stride(by: 3).forEach {
    print($0)
}
let nth = array.every(nth: 3)  // [1, 4, 7, 10, 13]

let str = "0123456789"
for character in str.stride(by: 2) {
    print(character)
}
str.stride(by: 2).forEach {
    print($0)
}
let even = str.every(nth: 2)   // "02468"

这篇关于通过抽取或提取Swift中的第n个元素来进行下采样收集的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 05:26