Created
June 6, 2024 17:13
-
-
Save simonbromberg/ec30d3bc9eb09cd1557ea85c700c03dc to your computer and use it in GitHub Desktop.
Sample a square subset of a 2D array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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