Created
April 26, 2019 22:37
-
-
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
This file contains hidden or 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 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