algorithm - creating a spiral array in python? -
me , mate trying create fun game in python elements entered in array accessed in spiral manner. have tried few methods 1 given below (source).
def spiral(x, y): x = y = 0 dx = 0 dy = -1 in range(max(x, y)**2): if (-x/2 < x <= x/2) , (-y/2 < y <= y/2): print (x, y) # stuff... if x == y or (x < 0 , x == -y) or (x > 0 , x == 1-y): dx, dy = -dy, dx x, y = x+dx, y+dy
the above statement accesses elements in spiral loop , prints them defined array ae. know how can transform given array ae spiral 1
you can build spiral starting near center of matrix , turning right unless element has been visited already:
#!/usr/bin/env python north, s, w, e = (0, -1), (0, 1), (-1, 0), (1, 0) # directions turn_right = {north: e, e: s, s: w, w: north} # old -> new direction def spiral(width, height): if width < 1 or height < 1: raise valueerror x, y = width // 2, height // 2 # start near center dx, dy = north # initial direction matrix = [[none] * width _ in range(height)] count = 0 while true: count += 1 matrix[y][x] = count # visit # try turn right new_dx, new_dy = turn_right[dx,dy] new_x, new_y = x + new_dx, y + new_dy if (0 <= new_x < width , 0 <= new_y < height , matrix[new_y][new_x] none): # can turn right x, y = new_x, new_y dx, dy = new_dx, new_dy else: # try move straight x, y = x + dx, y + dy if not (0 <= x < width , 0 <= y < height): return matrix # go def print_matrix(matrix): width = len(str(max(el row in matrix el in row if el not none))) fmt = "{:0%dd}" % width row in matrix: print(" ".join("_"*width if el none else fmt.format(el) el in row))
example:
>>> print_matrix(spiral(5, 5)) 21 22 23 24 25 20 07 08 09 10 19 06 01 02 11 18 05 04 03 12 17 16 15 14 13
Comments
Post a Comment