Skip to content

Instantly share code, notes, and snippets.

@joejag
Last active May 7, 2022 15:06
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 joejag/37b40736568de611623a7ef81c03c1e5 to your computer and use it in GitHub Desktop.
Save joejag/37b40736568de611623a7ef81c03c1e5 to your computer and use it in GitHub Desktop.

2D Spiral Array

Find the pattern and complete the function: int[][] spiral(int n) where n is the size of the 2D array.

Sample Result

input = 3
123
894
765

input = 4
01 02 03 04
12 13 14 05
11 16 15 06
10 09 08 07

input = 8
1 2 3 4 5 6 7 8
28 29 30 31 32 33 34 9
27 48 49 50 51 52 35 10
26 47 60 61 62 53 36 11
25 46 59 64 63 54 37 12
24 45 58 57 56 55 38 13
23 44 43 42 41 40 39 14
22 21 20 19 18 17 16 15
from itertools import cycle
def spiral(n):
grid = [[0 for x in range(n)] for y in range(n)]
directions = cycle([
lambda x,y: [x+1, y],
lambda x,y: [x, y+1],
lambda x,y: [x-1, y],
lambda x,y: [x, y-1]
])
current_direction = next(directions)
current_cord = [0, 0]
for num in range(0, n * n):
x, y = current_cord
grid[y][x] = num+1
cx, cy = current_direction(x, y)
if cx < 0 or cx >= n or cy < 0 or cy >= n or grid[cy][cx] != 0:
current_direction = next(directions)
current_cord = current_direction(x, y)
return grid
import unittest
class TestSpiralMethods(unittest.TestCase):
def test_one(self):
self.assertEqual(spiral(1), [[1]])
def test_two(self):
self.assertEqual(spiral(2), [
[1, 2],
[4, 3]])
def test_three(self):
self.assertEqual(spiral(3), [
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]])
unittest.main(exit=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment