Skip to content

Instantly share code, notes, and snippets.

@kemchenj
Last active November 2, 2020 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kemchenj/f9cec4babdd3931bf2dc9660cc5e7442 to your computer and use it in GitHub Desktop.
Save kemchenj/f9cec4babdd3931bf2dc9660cc5e7442 to your computer and use it in GitHub Desktop.
index
struct SampleCollection<C: RandomAccessCollection>: RandomAccessCollection {
let storage: C
let sampleInterval: Int
var startIndex: C.Index { storage.startIndex }
var endIndex: C.Index { storage.endIndex }
func index(before i: C.Index) -> C.Index {
if i == endIndex {
return storage.index(endIndex, offsetBy: -storage.count.remainderReportingOverflow(dividingBy: sampleInterval).partialValue)
} else {
return storage.index(i, offsetBy: -sampleInterval)
}
}
func index(after i: C.Index) -> C.Index { storage.index(i, offsetBy: sampleInterval, limitedBy: endIndex) ?? endIndex }
func distance(from start: C.Index, to end: C.Index) -> Int { storage.distance(from: start, to: end) / sampleInterval }
subscript(position: C.Index) -> C.Element { storage[position] }
init(sampleInterval: Int, storage: C) {
self.sampleInterval = sampleInterval
self.storage = storage
}
}
extension RandomAccessCollection {
func sample(interval: Int) -> SampleCollection<Self> {
SampleCollection(sampleInterval: interval, storage: self)
}
}
let array = [0, 1, 2, 3, 4, 5, 6]
let sampled = array.sample(interval: 2)
let firstIdx = sampled.startIndex // 0
let secondIdx = sampled.index(after: firstIdx) // 2
let numericDistance = secondIdx - firstIdx // 2
print(array.distance(from: firstIdx, to: secondIdx)) // 2
print(sampled.distance(from: firstIdx, to: secondIdx)) // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment