Last active
June 3, 2018 03:18
-
-
Save rakesh-patnaik/8fdc51680fc32fde8b2759e0f6b08e41 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# | |
#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 | |
def fillSquare(size, startValue, startRow, startCol, outputSquare): | |
for column in range(startCol, startCol + size): | |
outputSquare[startRow][column] = startValue | |
startValue += 1 | |
for row in range(startRow + 1, startRow + size): | |
outputSquare[row][startCol + size -1] = startValue | |
startValue += 1 | |
for column in reversed(range(startCol, startCol + size - 1)): | |
outputSquare[startRow + size - 1][column] = startValue | |
startValue += 1 | |
for row in reversed(range(startRow + 1, startRow + size - 1)): | |
outputSquare[row][startCol] = startValue | |
startValue += 1 | |
if(size - 2 >= 0): | |
fillSquare(size-2, startValue, startRow + 1, startCol + 1, outputSquare) | |
def main(): | |
size = input("input size of the spiral:") | |
if size < 0: | |
print "Sorry can only print squares of size > 0" | |
return | |
outputSquare = [[0]*size for i in range(size)] | |
fillSquare(size, 1, 0, 0, outputSquare) | |
for row in outputSquare: | |
print row | |
print "spiral of size %d is as follows:" % size | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment