Created
December 12, 2020 10:40
-
-
Save charlieInDen/f530824b77137ae3a013d82b13a1d99a to your computer and use it in GitHub Desktop.
This file contains 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
/// Input - [1, 2, 3, 6, 9, 8, 7, 4, 5], m = 3, n = 3 | |
func spiralTo2DMatrix(_ arr: [Int], row: Int, col: Int) -> [[Int]] { | |
/// Base condition | |
var result:[[Int]] = [[Int]]() | |
guard arr.isEmpty == false else { return result } | |
/// Logic | |
for _ in 0..<row { | |
result.append(Array(repeating: 0, count: col)) | |
} | |
var r1 = 0, c1 = 0 | |
var r2 = row - 1, c2 = col - 1 | |
var i = 0 | |
while r1 <= r2 && c1 <= c2 { | |
/// Go from c1 to c2 and append the element | |
for c in stride(from: c1, through: c2, by: 1) { | |
result[r1][c] = arr[i] | |
i = i + 1 | |
/// 1,2,3 | |
} | |
/// Go from next row till endof row | |
for r in stride(from: r1 + 1, through: r2, by: 1) { | |
result[r][c2] = arr[i] | |
i = i + 1 | |
} | |
if r1 < r2 && c1 < c2 { | |
/// Move from c2-1 till c1 | |
for c in stride(from: c2 - 1, through: c1, by: -1) { | |
result[r2][c] = arr[i] | |
i = i + 1 | |
} | |
/// Move from r2-1 till r1 | |
for r in stride(from: r2 - 1, to: r1, by: -1) { | |
result[r][c1] = arr[i] | |
i = i + 1 | |
} | |
} | |
r1 = r1 + 1 | |
r2 = r2 - 1 | |
c1 = c1 + 1 | |
c2 = c2 - 1 | |
} | |
return result | |
} | |
let flatInput = [1, 2, 3, 6, 9, 8, 7, 4, 5] | |
let newInput = [1, 2, 3, 4, 5, 6, 12, 18, 17, 16, 15, 14, 13, 7, 8, 9, 10, 11] | |
let m = 3, n = 3 | |
let spiralMatrix = spiralTo2DMatrix(newInput, row: 3, col: 6) | |
print(spiralMatrix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment