Skip to content

Instantly share code, notes, and snippets.

Created July 9, 2017 14:39
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 anonymous/f230ab574ced75248eef1a190d163fc6 to your computer and use it in GitHub Desktop.
Save anonymous/f230ab574ced75248eef1a190d163fc6 to your computer and use it in GitHub Desktop.
my solution to spiral ascension
# returns True/False if we need to turn
def at_edge(r, c, board, dir):
n = len(board) - 1
dir = dir.upper()
if (dir == 'N'):
return (r == 0) or (board[r - 1][c] != 0)
elif (dir == 'E'):
return (c == n) or (board[r][c + 1] != 0)
elif (dir == 'S'):
return (r == n) or (board[r + 1][c] != 0)
elif (dir == 'W'):
return (c == 0) or (board[r][c - 1] != 0)
else:
print "ERROR: dir is not N, E, S, W"
# returns the new direction after a turn
def turn(dir, clockwise):
if (dir == 'N'):
return 'E' if clockwise else 'W'
elif (dir == 'E'):
return 'S' if clockwise else 'N'
elif (dir == 'S'):
return 'W' if clockwise else 'E'
elif (dir == 'W'):
return 'N' if clockwise else 'S'
else:
print "ERROR: dir is not N, E, S, W"
# returns a tuple of the next (r, c) step going straight
def go_straight(r, c, dir):
if (dir == 'N'):
return (r - 1, c)
elif (dir == 'E'):
return (r, c + 1)
elif (dir == 'S'):
return (r + 1, c)
elif (dir == 'W'):
return (r, c - 1)
else:
print "ERROR: dir is not N, E, S, W"
# prints a spiral starting in the top-left (0, 0)
# bonus second parameter for counter-clockwise spiral
def solution(n, clockwise = True):
#initialize the board, number list, and row/col pair
board = [[0 for c in xrange(n)] for r in xrange(n)]
max_num = n ** 2
nums = range(1, max_num + 1)
r = c = 0
dir = 'E' if clockwise else 'S'
for i in nums:
# place the number on board
board[r][c] = i
# update r, c for next iteration
if at_edge(r, c, board, dir): dir = turn(dir, clockwise)
(r, c) = go_straight(r, c, dir)
# print a nice-looking board
width = len(str(max_num))
for row in board:
print ' '.join('{num:{fill}{width}}'.format(num=row[i], fill="", width=width) for i in xrange(n))
def main():
# acceptable values for n
proper_nums = [str(n) for n in range(36)]
print ("Hi, welcome to my solution to Spiral Ascenion...")
while (True):
n_str = raw_input("Input any number within [0,35] > ").strip()
if (n_str in proper_nums):
break
else:
print ("Oops! Try again...")
continue
clockwise = raw_input("Press Enter now for clockwise or input any other key for counter-clockwise > ")
clockwise = not bool(clockwise)
solution(int(n_str), clockwise)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment