Anonymous A started this discussion 5 months ago#128,230
Can somebody write code that takes an n by n matrix starting at the top left corner and numbers the positions in the matrix starting at 0 incrementing by one each time in counter-clockwise spiral order?
> Can somebody write code that takes an n by n matrix starting at the top left corner and numbers the positions in the matrix starting at 0 incrementing by one each time in counter-clockwise spiral order?
boof replied with this 5 months ago, 17 minutes later, 1 hour after the original post[^][v]#1,382,746
I notice that for n there are 2n - 1 direction turns
I notice that the number of numbers to place before turning is n, n - 1, n - 1, n - 2, n - 2, n - 3, n - 3, and so on continuing until n - x is 1 and no further.
Oatmeal Fucker !BYUc1TwJMU joined in and replied with this 5 months ago, 7 hours later, 8 hours after the original post[^][v]#1,382,790
Just vibecode it, it's the modern age
def counter_clockwise_spiral(n):
# Create n x n matrix filled with None
matrix = [[None] * n for _ in range(n)]
# Boundaries
top, bottom = 0, n - 1
left, right = 0, n - 1
num = 0 # Start number
while left <= right and top <= bottom:
# Top to bottom along left column
for i in range(top, bottom + 1):
matrix[i][left] = num
num += 1
left += 1
# Left to right along bottom row
for j in range(left, right + 1):
matrix[bottom][j] = num
num += 1
bottom -= 1
# Bottom to top along right column
if left <= right:
for i in range(bottom, top - 1, -1):
matrix[i][right] = num
num += 1
right -= 1
# Right to left along top row
if top <= bottom:
for j in range(right, left - 1, -1):
matrix[top][j] = num
num += 1
top += 1
return matrix
# Example usage:
n = 5
spiral = counter_clockwise_spiral(n)
for row in spiral:
print(" ".join(f"{x:2}" for x in row))
[/i][/i]