Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generating spiral matrices
def spiral(n)
arr = Array.new(n){Array.new(n){0}}
diff = [[0, 1], [1, 0], [0, -1], [-1, 0]]
i, j = 0, 0
dindex = 0
turns = 0
curr_square = n
shift = 0
(n*n).times do |index|
arr[i][j] = index + 1
if index == (shift + 4*curr_square - 5)
curr_square -= 2
turns, dindex = 0, 0
shift = index + 1
j += 1
next
end
i += diff[dindex][0]
j += diff[dindex][1]
if index == (shift + (turns + 1)*(curr_square - 1) - 1)
turns += 1
dindex += 1
end
end
arr
end
arr = spiral(10)
puts arr.map{|ia| ia.join(' ')}.join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment