Skip to content

Instantly share code, notes, and snippets.

@BrettBukowski
Created September 7, 2014 20:18
Show Gist options
  • Save BrettBukowski/4b4e55ce42865106c2c0 to your computer and use it in GitHub Desktop.
Save BrettBukowski/4b4e55ce42865106c2c0 to your computer and use it in GitHub Desktop.
Matrix rotation in swift
import Foundation
class Matrix {
var n = 0
private var matrix: Array<Array <Int>>
init(n: Int) {
self.n = n
self.matrix = Matrix.create(n)
}
func toString() -> String {
var str = ""
for i in 0..<matrix.count {
for j in 0..<matrix[i].count {
str += String(matrix[i][j]) + " "
}
str += "\n"
}
return str
}
func rotate(var _ degrees: Int = 90) {
if degrees % 90 != 0 {
NSException(name: "Disallowed", reason: "Not able to rotate a matrix \(degrees) degrees", userInfo: nil).raise()
}
var turns = degrees / 90
while turns > 0 {
turns--
rotate90Degrees()
}
}
func rotate90Degrees() {
for layer in 0..<n/2 {
var first = layer
var last = n - 1 - layer
for i in first..<last {
var offset = i - first
var top = matrix[first][i]
// top is now left
matrix[first][i] = matrix[last - offset][first]
// left is now bottom
matrix[last - offset][first] = matrix[last][last - offset]
// bottom is now right
matrix[last][last - offset] = matrix[i][last]
// right is now top
matrix[i][last] = top
}
}
}
private class func create(n: Int) -> Array<Array <Int>> {
var newMatrix = Array<Array <Int>>()
for i in 0..<n {
newMatrix.append(Array(count: n, repeatedValue: 0))
for j in 0..<n {
newMatrix[i][j] = Int(arc4random_uniform(9)) + 1
}
}
return newMatrix
}
}
var matrix = Matrix(n: 4)
println(matrix.toString())
matrix.rotate()
println("rotated 90°:")
println(matrix.toString())
matrix = Matrix(n: 4)
println(matrix.toString())
matrix.rotate(270)
println("rotated 270°:")
println(matrix.toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment