• + 0 comments

    swift

    func matrixRotation(matrix: [[Int]], r: Int) -> Void {
        // Write your code here
        let xCount: Int = matrix.count - 1
        let yCount: Int = matrix.first!.count - 1
    
        var coor: [[Int]] = [[Int]]()
        var flatMatrix: [Int] = [Int]()
        var newMatrix: [[Int]] = [[Int]](repeating: [Int](repeating: 0, count: yCount + 1), count: xCount + 1)
        var x: Int = 0
        var y: Int = -1
        var totalYRunSet: Int = 0
        var cycle: Int = 0
        var isIncrease: Bool = true
        var isYRun: Bool = true {
            didSet {
                totalYRunSet += 1
                if totalYRunSet % 4 == 0 { totalYRunSet = 0 }
                if totalYRunSet == 3 { cycle += 1 }
            }
        }
    
        while(true) {
            if isYRun {
                if isIncrease {
                    y += 1
                    if y == yCount - cycle { isYRun = false }
                }
                else {
                    y -= 1
                    if y == cycle { isYRun = false }
                }
            } else {
                if isIncrease {
                    x += 1
                    if x == xCount - cycle {
                        isYRun = true
                        isIncrease = false
                    }
                }
                else {
                    x -= 1
                    if x == cycle {
                        isYRun = true
                        isIncrease = true
                    }
                }
            }
            
            if newMatrix[x][y] == 1 { break }
      
            coor.append([x, y])
            newMatrix[x][y] = 1
        }
    
        for xy in coor { flatMatrix.append(matrix[xy[0]][xy[1]]) }
    
        var xyCount: [Int] = [xCount + 1, yCount + 1 ]
        var startIndex: Int = 0
        var newFlatMatrix: [Int] = [Int]()
    
        while(xyCount.min()! >= 2) {
            let total: Int = ((xyCount[0] * 2) + (xyCount[1] * 2)) - 4
            let slicedMatrix: [Int] = Array(flatMatrix[startIndex ... startIndex + total - 1])
            var index: Int = r % total
        
            if index == 0 { newFlatMatrix.append(contentsOf: slicedMatrix) }
            else {
                newFlatMatrix.append(slicedMatrix[index])
            
                while (index != (r % slicedMatrix.count) - 1) {
                    index += 1
                    if index == slicedMatrix.count { index = 0 }
                    newFlatMatrix.append(slicedMatrix[index])
                }
            }
            startIndex += total
            xyCount[0] -= 2
            xyCount[1] -= 2
        }
    
        for (mtrx, xy) in zip(newFlatMatrix, coor) { newMatrix[xy[0]][xy[1]] = mtrx }
    
        print(newMatrix.map{ $0.map{ String($0) }.joined(separator: " ") }.joined(separator: "\n"))
    }