Skip to content

Instantly share code, notes, and snippets.

@thedeagler
Created April 26, 2019 22:37
Show Gist options
  • Save thedeagler/1bf69b6090b6965467db491606845999 to your computer and use it in GitHub Desktop.
Save thedeagler/1bf69b6090b6965467db491606845999 to your computer and use it in GitHub Desktop.
Swift Array extension which creates a new 2d array, rotated 90 degrees clockwise from the original
extension Array where Element: Collection {
typealias InnerElement = Element.Element
/// Rotates a 2d array clockwise such that the nth column becomes the nth row. Rows which have
/// fewer elements than the longest row will be padded with nil to make a full, rectangular
/// matrix prior to rotation
///
/// - Returns: A rectangular matrix where the contents are rotated 90 degrees clockwise. Nil is
/// used as padding for rows/columns with fewer eleemnts than the max.
func rotatedClockwise() -> [[InnerElement?]] {
guard let numRows: Int = map({ $0.count }).max(), numRows > 0 else { return [[]] }
return map { row -> [InnerElement?] in
let row = row as! [InnerElement?] // Force casting is safe because Element === [InnerElement]
return row + [InnerElement?].init(repeating: nil, count: numRows - row.count)
}.reduce([[InnerElement?]].init(repeating: [], count: numRows)) { (matrix, row) in
row.enumerated().reduce(matrix) { (matrix, col) in
var matrix = matrix
matrix[col.offset].append(col.element)
return matrix
}
}.map {
$0.reversed()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment