62 lines
1.9 KiB
Swift
62 lines
1.9 KiB
Swift
//
|
|
// Array+Rotation.swift
|
|
// TetrisKit
|
|
//
|
|
// Created by Shadowfacts on 10/13/19.
|
|
// Copyright © 2019 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
extension Array where Element: RandomAccessCollection, Element: MutableCollection, Element.Index == Int {
|
|
mutating func rotateClockwise() {
|
|
guard allSatisfy({ $0.count == self.count }) else { return }
|
|
|
|
let layerCount = self.count / 2
|
|
|
|
for layer in 0..<layerCount {
|
|
let first = layer
|
|
let last = self.count - first - 1
|
|
|
|
for element in first..<last {
|
|
let offset = element - first
|
|
|
|
let top = self[first][element]
|
|
let rightSide = self[element][last]
|
|
let bottom = self[last][last - offset]
|
|
let leftSide = self[last - offset][first]
|
|
|
|
self[first][element] = leftSide
|
|
self[element][last] = top
|
|
self[last][last - offset] = rightSide
|
|
self[last - offset][first] = bottom
|
|
}
|
|
}
|
|
}
|
|
|
|
mutating func rotateCounterclockwise() {
|
|
guard allSatisfy({ $0.count == self.count }) else { return }
|
|
|
|
let layerCount = self.count / 2
|
|
|
|
for layer in 0..<layerCount {
|
|
let first = layer
|
|
let last = self.count - first - 1
|
|
|
|
for element in first..<last {
|
|
let offset = element - first
|
|
|
|
let top = self[first][element]
|
|
let rightSide = self[element][last]
|
|
let bottom = self[last][last - offset]
|
|
let leftSide = self[last - offset][first]
|
|
|
|
self[first][element] = rightSide
|
|
self[element][last] = bottom
|
|
self[last][last - offset] = leftSide
|
|
self[last - offset][first] = top
|
|
}
|
|
}
|
|
}
|
|
}
|