Skip to content

Instantly share code, notes, and snippets.

@simonbromberg
Created June 6, 2024 17:13
Show Gist options
  • Save simonbromberg/ec30d3bc9eb09cd1557ea85c700c03dc to your computer and use it in GitHub Desktop.
Save simonbromberg/ec30d3bc9eb09cd1557ea85c700c03dc to your computer and use it in GitHub Desktop.
Sample a square subset of a 2D array
extension Collection {
subscript(safeIndex index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
extension Array where Element: Collection, Element.Index == Int {
func samples(x: Int, y: Int, offset: Int) -> [Element.Element] {
var rows: [Element?] = []
for i in (y - offset)...(y + offset) {
rows.append(self[safeIndex: i])
}
return rows.compactMap { $0 }.map {
var values = [Element.Element?]()
for i in (x - offset)...(x + offset) {
values.append($0[safeIndex: i])
}
return values.compactMap { $0 }
}.flatMap { $0 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment