Created
January 30, 2014 16:30
-
-
Save ribtoks/8712591 to your computer and use it in GitHub Desktop.
Generating spiral matrices
This file contains hidden or 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
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