Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://www.reddit.com/r/dailyprogrammer/comments/3ggli3/20150810_challenge_227_easy_square_spirals/
- import math
- def spiral(*args):
- origin = [math.ceil(args[0]/2), math.ceil(args[0]/2)]
- if len(args) == 2: # when the input is a single value in the square spiral
- x = math.sqrt(args[1]) # finding the value of the next lower odd number squared
- y = math.floor(x)
- if y % 2 == 1:
- if x != y:
- pass
- else:
- y -= 2 # when x is an odd number and when the input value is an odd number squared
- else:
- y -= 1 # when x is an even number
- # adding from the value of the next lower odd number sqaured, i.e. 25, 49, etc.
- # and going around the square
- if y**2 < args[1] and args[1] <= y**2 + y + 1: # right side of square
- origin[0] = origin[0] + math.ceil(y/2)
- origin[1] = int(origin[1] + 0.5*(2*y**2 + y + 1) - args[1])
- elif y**2 + y + 1 < args[1] and args[1] <= y**2 + 2*y + 2: # top
- origin[0] = int(origin[0] + 0.5*(2*y**2+3*y+3) - args[1])
- origin[1] = origin[1] - math.ceil(y/2)
- elif y**2 + 2*y + 2 < args[1] and args[1] <= y**2 + 3*y + 3: # left
- origin[0] = origin[0] - math.ceil(y/2)
- origin[1] = int(origin[1] - 0.5*(2*y**2 + 5*y + 5) + args[1])
- elif y**2 + 3*y + 3 < args[1] and args[1] <= y**2 + 4*y + 4: # bottom
- origin[0] = int(origin[0] - 0.5*(2*y**2+7*y+7) + args[1])
- origin[1] = origin[1] + math.ceil(y/2)
- print(origin)
- else: # when the inputs are coordinates
- x = args[1]-origin[0] # finding coordinates relative to center
- y = -args[2]+origin[1]
- z = max([abs(x), abs(y)])
- value = 2*z - 1
- value1 = value ** 2 # value of the next lower odd number squared
- value2 = value+2
- value3 = (value2**2-value**2)/4 # increment
- # print(x,y,z,value,value1,value2,value3)
- if abs(y) >= abs(x) and y > 0: # top side of square
- answer = value1 + 1.5 * value3 - x
- elif abs(y) >= abs(x) and y < 0: # bottom
- answer = value1 + 3.5 * value3 + x
- elif abs(y) < abs(x) and x > 0: # right
- answer = value1 + 0.5 * value3 + y
- elif abs(y) < abs(x) and x < 0: # left
- answer = value1 + 2.5 * value3 - y
- print(answer)
- spiral(3, 8)
- spiral(11, 50)
- spiral(1024716039, 557614022)
- print()
- spiral(7, 1, 1)
- spiral(9, 6, 8)
- spiral(234653477, 11777272, 289722)
Add Comment
Please, Sign In to add comment