Last active
June 12, 2019 16:03
-
-
Save blenderskool/766e18bb34e4c8b36ed1fa0bac50bbf6 to your computer and use it in GitHub Desktop.
Generates a spiral pattern
This file contains 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
# This program generates a number spiral based on number entered by user | |
# Example: If input is 4, output is | |
# 01 02 03 04 | |
# 12 13 14 05 | |
# 11 16 15 06 | |
# 10 09 08 07 | |
i = 0 # Holds the position of row | |
j = 0 # Holds the position of column | |
di = 0 # Defines how i should change | |
dj = 1 # Defines how j should change | |
spiral = 0 # Keeps count of spirals | |
num = int(input('Enter a number: ')) | |
sq = num**2 | |
# Create a square matrix of order num x num | |
matrix = [ [0 for col in range(num)] for row in range(num)] | |
# Pattern generation | |
for val in range(1, sq+1): | |
# Set the value in the matrix | |
matrix[i][j] = val | |
# Control reaches top right | |
if j == num-1-spiral: | |
dj = 0 | |
di = 1 # Start moving down | |
# Control reaches bottom right | |
if i == num-1-spiral and j == num-1-spiral: | |
dj = -1 # Start moving left | |
di = 0 | |
# Control reaches bottom left | |
if i == num-1-spiral and j == spiral: | |
di = -1 # Start moving up | |
dj = 0 | |
# Control reaches top left | |
if i == spiral+1 and j == spiral: | |
di = 0 | |
dj = 1 # start moving right again | |
spiral += 1 # update spiral by 1, as 1 round of spiral is complete now | |
# Update values of i, j for next iteration | |
i += di | |
j += dj | |
# Output section | |
for row in matrix: | |
for val in row: | |
print("{:02d}".format(val), end=' ') | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment