Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ribtoks
Created January 30, 2014 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ribtoks/8712591 to your computer and use it in GitHub Desktop.
Save ribtoks/8712591 to your computer and use it in GitHub Desktop.
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