⚡ TL;DR
Print the spiral number matrix pattern in Swift. Complete working code, expected output, algorithm explanation, and practice variations for beginners learning loops.
The Spiral Number Matrix pattern is a classic loop exercise. Here’s the complete implementation in Swift with working code and output.
Pattern to Print
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9Implementation
func spiralMatrix(_ n: Int) {
var matrix = Array(repeating: Array(repeating: 0, count: n), count: n)
var num = 1, top = 0, bottom = n - 1, left = 0, right = n - 1
while top <= bottom && left <= right {
for i in left...right { matrix[top][i] = num; num += 1 }
top += 1
for i in top...bottom { matrix[i][right] = num; num += 1 }
right -= 1
if top <= bottom {
for i in stride(from: right, through: left, by: -1) { matrix[bottom][i] = num; num += 1 }
bottom -= 1
}
if left <= right {
for i in stride(from: bottom, through: top, by: -1) { matrix[i][left] = num; num += 1 }
left += 1
}
}
for row in matrix {
print(row.map { String(format: "%3d", $0) }.joined(separator: " "))
}
}
spiralMatrix(5)Output
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9How It Works
Layer-by-layer approach: walk the outer ring clockwise (top → right → bottom → left), then shrink the boundaries and repeat for the inner rings.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(1) — only loop counters are needed
Related Patterns
- Spiral Number Matrix in Python
- Spiral Number Matrix in Dart
- Spiral Number Matrix in Go
- Floyd’s Triangle in Swift
- Pascal’s Triangle in Swift
- Palindromic Number Pyramid in Swift
FAQ
How do you print the Spiral Number Matrix pattern in Swift?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Swift implementation with expected output is shown in the sections above.
What is the time complexity of the Spiral Number Matrix pattern in Swift?
The time complexity is O(n²) and the space complexity is O(1), since the pattern is built with a fixed number of loop counters and printed row by row.
Happy coding!
